import { Component, Event, h, Host, Prop, State } from '@stencil/core';
import CalendarUtils from "@dvn/core/util/calendar";
import { takvimCreateCustomAvailabilityFormI18nI18nDefault } from "@dvn/takvim/components/takvim-create-custom-availability-form/i18n";
import { SozlukApi } from '@dvn/sozluk/api';
import { CookieStorage } from "@dvn/kimlik/storage/cookie";
const defaultStartHour = 9;
const defaultEndHour = 10;
export class TakvimCreateCustomAvailabilityForm {
  constructor() {
    this.storage = new CookieStorage();
    this.breakDuration = 0;
    this.endHour = defaultEndHour;
    this.endMinute = 0;
    this.location = '';
    this.meetingDuration = 60;
    this.startHour = defaultStartHour;
    this.startMinute = 0;
    // giving locationType lastest meeting type
    this.locationType = this.storage.get('mt_lt') || 'custom';
    this.recurrence = 'weekly';
    this.errors = [];
    this.isProgressing = false;
    this.strings = takvimCreateCustomAvailabilityFormI18nI18nDefault;
    this.isRecurring = false;
    this.recurrenceDayIndex = 0;
    this.getDayDistanceForRecurringAvailability = () => {
      return (this.recurrenceDayIndex + 7 - this.date.getDay()) % 7;
    };
    this.onStartHourChange = (e) => {
      const { hour, minute } = e.detail;
      this.startDate = CalendarUtils.createDateWithHours(this.startDate, hour, minute);
      this.startHour = hour;
      this.startMinute = minute;
    };
    this.onEndHourChange = (e) => {
      const { hour, minute } = e.detail;
      this.endDate = CalendarUtils.createDateWithHours(this.endDate, hour, minute);
      this.endHour = hour;
      this.endMinute = minute;
    };
    this.onSubmit = () => {
      const { breakDuration, location, locationType, startDate, endDate, meetingDuration, recurrence } = this;
      const hasEmptyFields = this.validateForm();
      if (hasEmptyFields)
        return;
      const availability = {
        breakDuration,
        location: location,
        recurrence: this.availability
          ? this.availability.recurrence
          : (this.isRecurring ? recurrence : 'once'),
        locationType,
        startDate: startDate.toISOString(),
        endDate: endDate.toISOString(),
        meetingDuration,
        status: 'active',
        user: {
          _ref: 'kimlik-users',
          _id: this.user._id,
        }
      };
      this.isProgressing = true;
      if (this.availability) {
        availability._id = this.availability._id;
        this.apiTakvim.updateAvailability(availability)
          .then(() => this.updateAvailability.emit())
          .finally(() => this.isProgressing = false);
      }
      else {
        this.apiTakvim.createAvailability(availability)
          .then(() => this.createAvailability.emit())
          .finally(() => this.isProgressing = false);
      }
      // store lastest location type = lt
      this.storage.save('mt_lt', locationType);
    };
    this.onClickDelete = () => {
      this.isProgressing = true;
      this.apiTakvim.deleteAvailability(this.availability._id)
        .then(() => this.updateAvailability.emit())
        .finally(() => this.isProgressing = false);
    };
    this.validateForm = () => {
      const { location, locationType, strings, meetingDuration } = this;
      let hasError = false;
      const messages = [];
      if (locationType === 'custom' && location === '') {
        messages.push(SozlukApi.build(strings.emptyFieldError, { fieldName: strings.location }));
      }
      if (!meetingDuration) {
        messages.push(SozlukApi.build(strings.emptyFieldError, { fieldName: strings.meetingDuration }));
      }
      if (!locationType) {
        messages.push(SozlukApi.build(strings.emptyFieldError, { fieldName: strings.location }));
      }
      this.errors = messages;
      hasError = messages.length > 0;
      return hasError;
    };
  }
  componentWillLoad() {
    if (this.availability) {
      // editing availability
      this.startDate = new Date(this.availability.startDate);
      this.startHour = Number(CalendarUtils.format(this.startDate, 'H'));
      this.startMinute = Number(CalendarUtils.format(this.startDate, 'm'));
      this.endDate = new Date(this.availability.endDate);
      this.endHour = Number(CalendarUtils.format(this.endDate, 'H'));
      this.endMinute = Number(CalendarUtils.format(this.endDate, 'm'));
      this.meetingDuration = this.availability.meetingDuration;
      this.breakDuration = this.availability.breakDuration;
      this.location = this.availability.location;
      this.locationType = this.availability.locationType;
      this.recurrence = this.availability.recurrence;
      return;
    }
    const startDate = new Date(this.date);
    if (this.isRecurring) { // shift date to the next possible day (e.g. if monday is past, the next monday is picked)
      startDate.setDate(startDate.getDate() + this.getDayDistanceForRecurringAvailability());
    }
    this.startDate = CalendarUtils.createDateWithHours(startDate, defaultStartHour, 0);
    const endDate = new Date(this.date);
    if (this.isRecurring) { // shift date to the next possible day (e.g. if monday is past, the next monday is picked)
      endDate.setDate(endDate.getDate() + this.getDayDistanceForRecurringAvailability());
    }
    this.endDate = CalendarUtils.createDateWithHours(endDate, defaultEndHour, 0);
  }
  render() {
    const { availability, breakDuration, endHour, endMinute, location, recurrence, meetingDuration, startHour, startMinute, locationType, isProgressing, strings, } = this;
    let date = this.date;
    let isRecurring = this.isRecurring;
    if (availability) {
      date = new Date(availability.startDate);
      isRecurring = availability.recurrence !== 'once';
    }
    return (h(Host, null,
      h("dvn-dialog", { title: isRecurring
          ? strings.recurringAvailability
          : CalendarUtils.format(date, 'DD MMMM dddd, YYYY'), shown: true, width: '332px', onDismiss: (e) => {
          e.stopImmediatePropagation();
          if (this.isProgressing)
            return;
          this.dismiss.emit();
        } },
        this.errors.length > 0 &&
          h("div", { class: "form-errors-container my-2" }, this.errors.map(message => (h("p", { class: "formError" }, message)))),
        h("dvn-form-field", { fieldTitle: strings.recurrence, hidden: true },
          h("dvn-select", { leaned: true, value: `${recurrence}`, disabled: true },
            h("dvn-select-option", { value: "weekly" }, strings.weekly))),
        h("div", { class: "d-flex time-picker-container" },
          h("dvn-form-field", { required: true, fieldTitle: strings.startTime },
            h("dvn-time-picker", { leaned: true, hour: startHour, minute: startMinute, timeFormat: this.userSettings.timeFormat, onChange: this.onStartHourChange, disabled: isProgressing })),
          h("dvn-form-field", { required: true, fieldTitle: strings.endTime },
            h("dvn-time-picker", { leaned: true, hour: endHour, minute: endMinute, timeFormat: this.userSettings.timeFormat, onChange: this.onEndHourChange, disabled: isProgressing }))),
        h("dvn-form-field", { required: true, fieldTitle: strings.meetingDuration },
          h("dvn-select", { leaned: true, value: `${meetingDuration}`, onChange: e => this.meetingDuration = +e.detail, disabled: isProgressing },
            h("dvn-select-option", { value: "15" },
              "15 ",
              strings.minutes),
            h("dvn-select-option", { value: "30" },
              "30 ",
              strings.minutes),
            h("dvn-select-option", { value: "45" },
              "45 ",
              strings.minutes),
            h("dvn-select-option", { value: "60" },
              "60 ",
              strings.minutes),
            h("dvn-select-option", { value: "90" },
              "1.5 ",
              strings.hours),
            h("dvn-select-option", { value: "120" },
              "2 ",
              strings.hours),
            h("dvn-select-option", { value: "150" },
              "2.5 ",
              strings.hours),
            h("dvn-select-option", { value: "180" },
              "3 ",
              strings.hours))),
        h("dvn-form-field", { fieldTitle: strings.breakDuration },
          h("dvn-select", { leaned: true, value: `${breakDuration}`, onChange: e => this.breakDuration = +e.detail, disabled: isProgressing },
            h("dvn-select-option", { value: "0" }, "-"),
            h("dvn-select-option", { value: "5" },
              "5 ",
              strings.minutes),
            h("dvn-select-option", { value: "10" },
              "10 ",
              strings.minutes),
            h("dvn-select-option", { value: "15" },
              "15 ",
              strings.minutes))),
        h("dvn-form-field", { fieldTitle: strings.videoConferencePlatform, required: true },
          h("dvn-select", { leaned: true, value: locationType, onChange: e => this.locationType = e.detail, disabled: isProgressing },
            h("dvn-select-option", { value: "custom" }, strings.custom),
            h("dvn-select-option", { value: "jitsi" }, strings.jitsi),
            this.userSettings.authPlatforms.some(authPlatform => authPlatform.id === 'zoom') &&
              h("dvn-select-option", { value: "zoom" }, strings.zoom),
            this.userSettings.authPlatforms.some(authPlatform => authPlatform.id === 'google') &&
              h("dvn-select-option", { value: "google" }, strings.google),
            this.userSettings.authPlatforms.some(authPlatform => authPlatform.id === 'microsoftbusiness') &&
              h("dvn-select-option", { value: "microsoftbusiness" }, strings.microsoftbusiness))),
        this.locationType === 'custom' &&
          h("dvn-form-field", { fieldTitle: strings.location, required: true },
            h("dvn-input", { leaned: true, value: locationType !== 'custom' ? '-' : location, disabled: locationType !== 'custom' || isProgressing, onChange: e => this.location = e.detail })),
        h("div", { slot: "actions" },
          h("dvn-button", { view: "flat", onClick: () => this.dismiss.emit() }, strings.cancel),
          !!availability &&
            h("dvn-button", { view: "flat", tint: "danger", onClick: this.onClickDelete, disabled: isProgressing }, strings.deleteAvailability),
          h("dvn-button", { view: "flat", tint: "primary", onClick: this.onSubmit, disabled: isProgressing }, availability ? strings.updateAvailability : strings.createAvailability)))));
  }
  static get is() { return "takvim-create-custom-availability-form"; }
  static get originalStyleUrls() { return {
    "$": ["takvim-create-custom-availability-form.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["takvim-create-custom-availability-form.css"]
  }; }
  static get properties() { return {
    "apiTakvim": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "TakvimApi",
        "resolved": "TakvimApi",
        "references": {
          "TakvimApi": {
            "location": "import",
            "path": "@dvn/takvim/api/takvimApi"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "strings": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "TakvimCreateCustomAvailabilityFormI18n",
        "resolved": "TakvimCreateCustomAvailabilityFormI18n",
        "references": {
          "TakvimCreateCustomAvailabilityFormI18n": {
            "location": "import",
            "path": "@dvn/takvim/components/takvim-create-custom-availability-form/i18n"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "defaultValue": "takvimCreateCustomAvailabilityFormI18nI18nDefault"
    },
    "user": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "User",
        "resolved": "User",
        "references": {
          "User": {
            "location": "import",
            "path": "@dvn/kimlik/api/models"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "userSettings": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "UserSettings",
        "resolved": "UserSettings",
        "references": {
          "UserSettings": {
            "location": "import",
            "path": "@dvn/kimlik/api/models/UserSettings"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "date": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Date",
        "resolved": "Date",
        "references": {
          "Date": {
            "location": "global"
          }
        }
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "isRecurring": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "is-recurring",
      "reflect": false,
      "defaultValue": "false"
    },
    "recurrenceDayIndex": {
      "type": "number",
      "mutable": false,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "recurrence-day-index",
      "reflect": false,
      "defaultValue": "0"
    },
    "availability": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Availability",
        "resolved": "Availability",
        "references": {
          "Availability": {
            "location": "import",
            "path": "@dvn/takvim/api/models"
          }
        }
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      }
    }
  }; }
  static get states() { return {
    "breakDuration": {},
    "endHour": {},
    "endMinute": {},
    "location": {},
    "meetingDuration": {},
    "startHour": {},
    "startMinute": {},
    "locationType": {},
    "recurrence": {},
    "startDate": {},
    "endDate": {},
    "errors": {},
    "isProgressing": {}
  }; }
  static get events() { return [{
      "method": "dismiss",
      "name": "dismiss",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }, {
      "method": "createAvailability",
      "name": "createAvailability",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }, {
      "method": "updateAvailability",
      "name": "updateAvailability",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }]; }
}
