import { ICourse, IChapter, CmsItem, initCmsItem } from "../schema";
import { Api } from "./Api";
import { Chapter } from "./Chapter";
import { UtilButton } from "./UtilButton";

export class Course {
  course: CmsItem<ICourse, any>;
  chapters: Chapter[] = [];
  dom: HTMLDivElement;
  parent: HTMLElement;
  contentSection: HTMLDivElement;
  mode: "edit" | "preview" | "live" = "edit";

  constructor(
    data: CmsItem<ICourse, any>,
    parent: HTMLElement,
    mode: "edit" | "preview" | "live" = "edit"
  ) {
    this.course = data;
    this.mode = mode;
    this.contentSection = document.querySelector(
      "#content-section"
    ) as HTMLDivElement;
    this.dom = document.createElement("div");
    this.course.children?.forEach((chapter, index) => {
      if (chapter?.data) {
        const newChapter = new Chapter(chapter, index, this);
        this.chapters.push(newChapter);
      }
    });
    this.parent = parent;
    if (this.parent) {
      this.chapters.forEach((chapter) => {
        this.dom.appendChild(chapter.dom);
      });
      this.parent.appendChild(this.dom);
    }
    this.isEdit && this.renderAddChapterButton();
  }
  get isPreview() {
    return this.mode === "preview";
  }
  get isEdit() {
    return this.mode === "edit";
  }
  get isLive() {
    return this.mode === "live";
  }
  renderAddChapterButton() {
    const addChapterButton = new UtilButton(this.dom, "Add Chapter");
    addChapterButton.button.classList.add("sticky-bottom");
    addChapterButton.button.onclick = () => {
      this.addChapter();
    };
  }
  addChapter() {
    const initChapter = initCmsItem<IChapter, any>(
      { Lessons: [], Name: "Untitled Chapter" },
      {
        created: new Date(),
      },
      "Untitled Chapter",
      this.course.id + "",
      this.course.parent_id
    );
    const newChapter = new Chapter(initChapter, this.chapters.length, this);
    this.chapters.push(newChapter);
    this.dom.appendChild(newChapter.dom);
    const api = new Api();
    api
      .postCall("https://cms.tybo.co.za/api/cms/add-data-item.php", initChapter)
      .then((data) => {
        console.log(data);
        location.reload();
      });
  }
}
