import { formatImperialDate } from './calendarDate.js';

const { ApplicationV2, HandlebarsApplicationMixin } = foundry.applications.api;
const MODULE_ID = 'mgt2-compendium-amiral-denisov';

export class CalendarApp extends HandlebarsApplicationMixin(ApplicationV2) {
  static DEFAULT_OPTIONS = {
    id: 'mgt2-calendar',
    classes: ['mgt2-calendar'],
    position: { width: 260, height: 'auto' },
    window: {
      icon: 'fas fa-calendar-alt',
      title: 'Calendrier Impérial',
      resizable: false,
    },
  };

  static PARTS = {
    main: {
      template: `modules/${MODULE_ID}/templates/calendar-app.hbs`,
      root: true,
    },
  };

  constructor({ onConfig, onClose, onNote } = {}) {
    super();
    const saved = game.settings?.get(MODULE_ID, 'calendarPosition');
    if (saved?.left != null && saved?.top != null) {
      this.position.left = saved.left;
      this.position.top = saved.top;
    }
    this._onConfig = onConfig;
    this._onClose = onClose;
    this._onNote = onNote;
    this._data = { year: 1116, day: 1, hour: 12, minute: 0, planet: '' };
  }

  get title() {
    return 'Calendrier Impérial';
  }

  async _prepareContext() {
    return {
      dateLabel: formatImperialDate(this._data),
      isGM: game.user?.isGM ?? false,
    };
  }

  async _onRender(context, options) {
    await super._onRender(context, options);
    const html = $(this.element);
    html.find('.mgt2-cal-config-btn').on('click', () => {
      this._onConfig?.();
    });
    html.find('.mgt2-cal-note-btn').on('click', () => {
      this._onNote?.();
    });
  }

  setPosition(position) {
    const result = super.setPosition(position);
    this._debouncedSavePos();
    return result;
  }

  _debouncedSavePos() {
    if (this._savePosTimeout) clearTimeout(this._savePosTimeout);
    this._savePosTimeout = setTimeout(() => {
      game.settings?.set(MODULE_ID, 'calendarPosition', {
        left: this.position.left,
        top: this.position.top,
      });
      this._savePosTimeout = null;
    }, 300);
  }

  updateDisplay(data) {
    this._data = { ...this._data, ...data };
    this.render();
  }

  async close() {
    if (game.settings) {
      await game.settings.set(MODULE_ID, 'calendarPosition', {
        left: this.position.left,
        top: this.position.top,
      });
    }
    this._onConfig = null;
    this._onNote = null;
    this._onClose?.();
    this._onClose = null;
    return super.close();
  }
}
