import { SYSTEM_RDD } from "./constants.js";
import { Grammar } from "./grammar.js";
import { HtmlUtility } from "./html-utility.js";
import { RdDTimestamp } from "./rdd-timestamp.js";


const LATEST_USED_JOURNAL_ID = "chronologie-dernier-journal";

export class DialogChronologie extends Dialog {

  static init() {
    game.settings.register(SYSTEM_RDD, LATEST_USED_JOURNAL_ID, {
      name: "Dernier article de journal utilisé pour enregistrer la chronologie",
      scope: "client",
      config: false,
      default: "",
      type: String
    });
  }
  static async create() {
    const dialogData = {
      auteur: game.user.name,
      isGM: game.user.isGM,
      information: "",
      journalId: game.settings.get(SYSTEM_RDD, LATEST_USED_JOURNAL_ID),
      journaux: game.journal.filter(it => it.testUserPermission(game.user, CONST.DOCUMENT_OWNERSHIP_LEVELS.OWNER)),
      timestamp: game.system.rdd.calendrier.timestamp,
      dateReel: DialogChronologie.getCurrentDateTime()
    };
    const html = await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/dialog-chronologie.html", dialogData);
    const dialog = new DialogChronologie(html, dialogData);
    dialog.render(true);
  }

  static getCurrentDateTime() {
    return new Date().toLocaleString("sv-SE", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit"
    }).replace(" ", "T");
  }

  constructor(html, dialogData) {
    const options = {
      classes: ["DialogChronologie"],
      width: 500,
      height: 'fit-content',
      'z-index': 99999
    };
    const timeData = dialogData.timestamp.toCalendrier()
    const conf = {
      title: `Chronologie - ${timeData.jourDuMois} ${timeData.mois.label} - Heure  ${timeData.heure.label}`,
      content: html,
      buttons: {
      }
    };
    super(conf, options);
    this.dialogData = dialogData;
  }

  activateListeners(html) {
    this.html = html;
    super.activateListeners(html);
    const journalPrecedent = game.journal.get(this.dialogData.journalId);
    this.showChronologiePreset(!(journalPrecedent?.canUserModify(game.user)))

    this.html.find("a.chronologie-preset-show").click(event => this.showChronologiePreset(true));
    this.html.find("a.chronologie-preset-hide").click(event => this.showChronologiePreset(false));
    this.html.find("button.chronologie-ajouter").click(event => this.ajouter());
  }

  showChronologiePreset(showPreset) {
    HtmlUtility.showControlWhen(this.html.find(".chronologie-preset-show"), !showPreset);
    HtmlUtility.showControlWhen(this.html.find(".chronologie-preset-hide"), showPreset);
    HtmlUtility.showControlWhen(this.html.find(".chronologie-preset"), showPreset);
  }

  async ajouter() {
    await this.forceValidation();
    const { journalId, journalEntry } = this.findJournal();
    if (journalEntry?.canUserModify(game.user)) {
      const journalParameters = this.extractJournalParameters();

      const jour = journalParameters.dateRdD.jour;
      const mois = journalParameters.dateRdD.mois.label;
      const annee = journalParameters.dateRdD.annee;
      const section = `${jour} ${mois} ${annee}`
      const content = await this.prepareChronologieEntry(journalParameters);
      // ajouter à la page ou créer une page
      this.addContentToJournal(journalEntry, section, content);
      this.storeLatestUsedJournalEntry(journalId);
      this.close();
    }
    else {
      const journal = this.html.find("form.rdddialogchrono select[name='journalId']").val();
      ui.notifications.warn(`Le journal ${journal} n'est pas accessible`);
    }
  }

  async forceValidation() {
    await this.html.find("form.rdddialogchrono :input").change();
  }

  findJournal() {
    const journalId = this.html.find("form.rdddialogchrono :input[name='journalId']").val();
    const journalEntry = game.journal.get(journalId);
    return { journalId, journalEntry };
  }

  async prepareChronologieEntry(journalParameters) {
    return await renderTemplate("systems/foundryvtt-reve-de-dragon/templates/chronologie-entry.html", journalParameters);
  }

  extractJournalParameters() {
    return {
      auteur: this.html.find("form.rdddialogchrono :input[name='auteur']").val(),
      information: this.html.find("form.rdddialogchrono :input[name='information']").val(),
      dateRdD: {
        jour: this.html.find("form.rdddialogchrono :input[name='chronologie.jourDuMois']").val(),
        mois: RdDTimestamp.definition(this.html.find("form.rdddialogchrono :input[name='chronologie.mois']").val()),
        annee: this.html.find("form.rdddialogchrono :input[name='chronologie.annee']").val(),
        heure: RdDTimestamp.definition(this.html.find("form.rdddialogchrono :input[name='chronologie.heure']").val()),
        minute: this.html.find("form.rdddialogchrono :input[name='chronologie.minute']").val(),
      },
      dateReel: this.html.find("form.rdddialogchrono :input[name='dateReel']").val().replace('T', ' ')
    }
  }

  addContentToJournal(journalEntry, section, content) {
    let page = journalEntry.pages.find(p => p.type == 'text' && Grammar.equalsInsensitive(p.name, section));
    if (page) {
      page.update({ 'text.content': page.text.content + '\n' + content });
    }
    else {
      journalEntry.createEmbeddedDocuments('JournalEntryPage', [this.newPageChronologie(section, content)]);
    }
  }

  newPageChronologie(section, content) {
    return new JournalEntryPage({
      name: section,
      type: 'text',
      title: { show: true, level: 1 },
      text: { content: content, format: 1 }
    });
  }

  storeLatestUsedJournalEntry(journalId) {
    game.settings.set(SYSTEM_RDD, LATEST_USED_JOURNAL_ID, journalId);
  }
}