import { ILesson } from "../schema";
import { Chapter } from "./Chapter";
import { EditLesson } from "./EditLesson";
import { ViewLesson } from "./ViewLesson";

export class Lesson {
  lesson: ILesson;
  chapter: Chapter;
  dom: HTMLAnchorElement;
  editHandler: EditLesson;
  viewLesson: ViewLesson;
  contentSection: HTMLDivElement;
  index: number;
  constructor(data: ILesson, index: number, chapter: Chapter) {
    this.lesson = data;
    this.index = index;
    this.chapter = chapter;
    this.dom = document.createElement("a");
    this.contentSection = document.querySelector(
      "#content-section"
    ) as HTMLDivElement;
    this.configure();
    this.editHandler = new EditLesson(this);
    this.viewLesson = new ViewLesson(this);
    this.addEvents();
    if (
      chapter.course.isPreview &&
      this.isFirstLesson &&
      this.chapter.isFirstChapter
    ) {
      this.openView();
    }
  }
  get isFirstLesson() {
    return this.index === 0;
  }
  configure() {
    this.dom.href = "#";
    this.dom.classList.add("list-group-item", "list-group-item-action");
    const p = document.createElement("p");
    p.innerHTML = this.lesson.Title;
    const badge = document.createElement("span");
    badge.classList.add("badge", "text-bg-info");
    badge.innerHTML = this.lesson.Type;
    this.dom.appendChild(p);
    this.dom.appendChild(badge);
  }
  addEvents() {
    this.dom.onpointerup = () => {
      this.openEdit();
    };
  }
  openEdit() {
    if (this.chapter.course.isPreview) {
      this.openView();
      return;
    }
    this.contentSection.innerHTML = "";
    this.contentSection.appendChild(this.editHandler.dom);
  }
  openView() {
    this.contentSection.innerHTML = "";
    this.contentSection.appendChild(this.viewLesson.dom);
  }
}
