import { Component, Event, h, Listen, Prop, State, Watch } from '@stencil/core';
import { StateOfReminder } from '../../utils/utils';
import { DateTime } from 'luxon';
export class SwAddonReminder {
  constructor() {
    this.badgeErrorOn = false;
    this.isFirstTime = true;
    this.submitAlreadyTriggered = false;
    // Props:
    this.sendDataForCalendar = false;
    this.withoutFooter = false;
    this.deleteSub = false;
    this.userInfo = { name: 'Nome', surname: 'Cognome', date: 'creato oggi', image: 'assets/img/user.svg' };
    this.state = '';
    this.taskId = 722;
    this.idPluginAction = 9;
    this.baseUrl = 'https://app.dev.synbee.it';
    this.idPluginActionExternal = 22;
    // States:
    this.reminderDone = false;
    this.status = StateOfReminder.create;
    this.reminderInfo = {
      name: 'Nuova Action Promemoria',
      description: '',
      hour: '00',
      minute: '00',
      duration: '00',
      date: ''
    };
  }
  catchUndoReminder() {
    if (this.status === StateOfReminder.edit) {
      this.status = StateOfReminder.view;
    }
    else {
      this.undoReminderOutEmitter.emit(true);
    }
  }
  catchCloseAction(ev) {
    this.collapseReminder.emit(ev.detail);
  }
  //create reminder from calendar:
  sendOutputDataFromCalendar() {
    let outputToChange = Object.assign({}, this.reminderInfo);
    let arrayDate = this.reminderInfo.date.split('/');
    let month;
    if (arrayDate[1]) {
      if (arrayDate[1].startsWith('0')) {
        month = parseInt(arrayDate[1].replace('0', ''));
        month = month - 1;
      }
      else {
        month = parseInt(arrayDate[1]);
        month = month - 1;
      }
    }
    let newHour = parseInt(this.reminderInfo.hour.startsWith('0') ? this.reminderInfo.hour.replace('0', '') : this.reminderInfo.hour) + parseInt(this.reminderInfo.duration.startsWith('0') ? this.reminderInfo.duration.replace('0', '') : this.reminderInfo.duration);
    outputToChange.dateTime = new Date(arrayDate[2], month, arrayDate[0], this.reminderInfo.hour.startsWith('0') ? this.reminderInfo.hour.replace('0', '') : this.reminderInfo.hour, this.reminderInfo.minute);
    outputToChange.dateTimeEnd = new Date(arrayDate[2], month, arrayDate[0], newHour, this.reminderInfo.minute);
    let startDate = DateTime.fromJSDate(outputToChange.dateTime).toISO({ includeOffset: false });
    let endDate = DateTime.fromJSDate(outputToChange.dateTimeEnd).toISO({ includeOffset: false });
    let body = { name: outputToChange.name, description: outputToChange.description, startDate: startDate, endDate: endDate };
    if (this.taskId !== null) {
      fetch(`${this.baseUrl}/services/eolo-api-gateway/external-api/${this.taskId}/${this.idPluginAction}`, {
        method: 'POST',
        body: JSON.stringify(body),
        headers: {
          "Content-Type": "application/json"
        }
      })
        .then((response) => response.json())
        .then(response => {
        this.outputDataEmitter.emit(response);
      });
    }
  }
  // create reminder:
  sendOutputData(ev) {
    let outputToChange = Object.assign({}, ev.detail);
    let arrayDate = ev.detail.date.split('/');
    let month;
    if (arrayDate[1]) {
      if (arrayDate[1].startsWith('0')) {
        month = parseInt(arrayDate[1].replace('0', ''));
        month = month - 1;
      }
      else {
        month = parseInt(arrayDate[1]);
        month = month - 1;
      }
    }
    let newHour = parseInt(ev.detail.hour.startsWith('0') ? ev.detail.hour.replace('0', '') : ev.detail.hour) + parseInt(ev.detail.duration.startsWith('0') ? ev.detail.duration.replace('0', '') : ev.detail.duration);
    outputToChange.dateTime = new Date(arrayDate[2], month, arrayDate[0], ev.detail.hour.startsWith('0') ? ev.detail.hour.replace('0', '') : ev.detail.hour, ev.detail.minute);
    outputToChange.dateTimeEnd = new Date(arrayDate[2], month, arrayDate[0], newHour, ev.detail.minute);
    let startDate = DateTime.fromJSDate(outputToChange.dateTime).toISO({ includeOffset: false });
    let endDate = DateTime.fromJSDate(outputToChange.dateTimeEnd).toISO({ includeOffset: false });
    let body = { name: outputToChange.name, description: outputToChange.description, startDate: startDate, endDate: endDate };
    fetch(`${this.baseUrl}/services/eolo-api-gateway/external-api/${this.taskId}/${this.idPluginAction}`, {
      method: 'POST',
      body: JSON.stringify(body),
      headers: {
        "Content-Type": "application/json"
      }
    })
      .then((response) => response.json())
      .then(response => {
      this.outputDataEmitter.emit(response);
    });
  }
  // edit reminder:
  editOutputData(ev) {
    let outputToChange = Object.assign({}, ev.detail);
    let arrayDate = ev.detail.date.split('/');
    let month;
    if (arrayDate[1]) {
      if (arrayDate[1].startsWith('0')) {
        month = parseInt(arrayDate[1].replace('0', ''));
        month = month - 1;
      }
      else {
        month = parseInt(arrayDate[1]);
        month = month - 1;
      }
    }
    let newHour = parseInt(ev.detail.hour.startsWith('0') ? ev.detail.hour.replace('0', '') : ev.detail.hour) + parseInt(ev.detail.duration.startsWith('0') ? ev.detail.duration.replace('0', '') : ev.detail.duration);
    outputToChange.dateTime = new Date(arrayDate[2], month, arrayDate[0], ev.detail.hour.startsWith('0') ? ev.detail.hour.replace('0', '') : ev.detail.hour, ev.detail.minute);
    outputToChange.dateTimeEnd = new Date(arrayDate[2], month, arrayDate[0], newHour, ev.detail.minute);
    let startDate = DateTime.fromJSDate(outputToChange.dateTime).toISO({ includeOffset: false });
    let endDate = DateTime.fromJSDate(outputToChange.dateTimeEnd).toISO({ includeOffset: false });
    let body = { name: outputToChange.name, description: outputToChange.description, startDate: startDate, endDate: endDate, actionRead: this.reminderDone };
    fetch(`${this.baseUrl}/services/eolo-api-gateway/external-api/${this.idPluginAction}/${this.idPluginActionExternal}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(body)
    }).then(response => response.json())
      .then(response => {
      return this.editOutputDataEmitter.emit(response);
    })
      .catch(err => {
      console.log(err);
    });
  }
  catchErrorFromUncomplitedDate(ev) {
    this.submitAlreadyTriggered = true;
    this.badgeErrorOn = ev.detail === true;
  }
  setReminderDone(ev) {
    this.reminderDone = ev.detail;
    this.isFirstTime = false;
    this.reminderDoneSetter.emit(this.reminderDone);
    let outputToChange = Object.assign({}, this.reminderInfo);
    let arrayDate = outputToChange.date.split('/');
    let month;
    if (arrayDate[1]) {
      if (arrayDate[1].startsWith('0')) {
        month = parseInt(arrayDate[1].replace('0', ''));
        month = month - 1;
      }
      else {
        month = parseInt(arrayDate[1]);
        month = month - 1;
      }
    }
    let newHour = parseInt(outputToChange.hour.startsWith('0') ? outputToChange.hour.replace('0', '') : outputToChange.hour) + parseInt(outputToChange.duration.startsWith('0') ? outputToChange.duration.replace('0', '') : outputToChange.duration);
    outputToChange.dateTime = new Date(parseInt(arrayDate[2]), month, parseInt(arrayDate[0]), outputToChange.hour.startsWith('0') ? parseInt(outputToChange.hour.replace('0', '')) : parseInt(outputToChange.hour), parseInt(outputToChange.minute));
    outputToChange.dateTimeEnd = new Date(parseInt(arrayDate[2]), month, parseInt(arrayDate[0]), newHour, parseInt(outputToChange.minute));
    let startDate = DateTime.fromJSDate(outputToChange.dateTime).toISO({ includeOffset: false });
    let endDate = DateTime.fromJSDate(outputToChange.dateTimeEnd).toISO({ includeOffset: false });
    let body = { name: outputToChange.name, description: outputToChange.description, startDate: startDate, endDate: endDate, actionRead: this.reminderDone };
    fetch(`${this.baseUrl}/services/eolo-api-gateway/external-api/${this.idPluginAction}/${this.idPluginActionExternal}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(body)
    }).then(response => response.json())
      .then(response => {
      return this.editOutputDataEmitter.emit(response);
    })
      .catch(err => {
      console.log(err);
    });
  }
  // delete reminder:
  changeStat(ev) {
    if (ev.detail === 'edit') {
      this.status = StateOfReminder.edit;
    }
    else {
      fetch(`${this.baseUrl}/services/eolo-api-gateway/external-api/${this.idPluginAction}/${this.idPluginActionExternal}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json'
        }
      })
        .then(() => {
        console.log('removed');
        return this.deleteAddonReminderEmitter.emit(true);
      })
        .catch(err => {
        console.log(err);
      });
    }
  }
  createReminder() {
    this.status = StateOfReminder.view;
  }
  takeInfoFromBody(ev) {
    let reminder = Object.assign({}, this.reminderInfo);
    if (ev.detail.hour) {
      reminder.hour = ev.detail.hour;
    }
    if (ev.detail.minute) {
      reminder.minute = ev.detail.minute;
    }
    if (ev.detail.duration) {
      reminder.duration = ev.detail.duration;
    }
    if (ev.detail.description) {
      reminder.description = ev.detail.description;
    }
    if (ev.detail.date) {
      reminder.date = ev.detail.date;
    }
    this.reminderInfo = Object.assign({}, reminder);
  }
  takeInfoFromHeder(ev) {
    let reminder = Object.assign({}, this.reminderInfo);
    reminder.name = ev.detail;
    this.reminderInfo = Object.assign({}, reminder);
  }
  deleteFromActionClose() {
    if (this.deleteSub) {
      fetch(`${this.baseUrl}/services/eolo-api-gateway/external-api/${this.idPluginAction}/${this.idPluginActionExternal}`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json'
        }
      })
        .then(() => {
        console.log('removed');
        return this.deleteAddonReminderEmitter.emit(true);
      })
        .catch(err => {
        console.log(err);
      });
    }
  }
  stateDetectionChange() {
    if (this.state === 'view') {
      this.status = StateOfReminder.view;
    }
  }
  validationOfData(newValue) {
    if (this.submitAlreadyTriggered) {
      if (this.withoutFooter) {
        if (newValue.endDate && newValue.startDate && newValue.name && newValue.description) {
          this.badgeErrorOn = false;
          this.validation = true;
        }
        else {
          this.validation = false;
          this.badgeErrorOn = true;
        }
      }
      else {
        if (newValue.hour && newValue.minute && newValue.duration && newValue.description && newValue.date && newValue.name && this.reminderInfo.date) {
          this.badgeErrorOn = false;
          this.validation = true;
        }
        else {
          this.validation = false;
          this.badgeErrorOn = true;
        }
      }
    }
  }
  componentShouldUpdate() {
    if (this.sendDataForCalendar) {
      this.validationOfData(this.reminderInfoDTO);
      if (this.validation) {
        this.sendOutputDataFromCalendar();
      }
      else {
        this.badgeErrorOn = true;
      }
    }
  }
  componentWillRender() {
    if (this.isFirstTime) {
      this.reminderDone = this.doneFlag;
      if (this.state) {
        if (this.state === 'view') {
          this.status = StateOfReminder.view;
          // qui faccio il mapper de merda:
          this.reminderInfo.name = this.reminderInfoDTO.name;
          this.reminderInfo.description = this.reminderInfoDTO.description;
          let startDate = new Date(this.reminderInfoDTO.startDate);
          let endDate = new Date(this.reminderInfoDTO.endDate);
          this.reminderInfo.date = DateTime.fromJSDate(startDate).toLocal().toFormat('dd/MM/yyyy');
          if (startDate.getHours() < 10) {
            this.reminderInfo.hour = '0' + String(startDate.getHours());
            this.reminderInfo.minute = String(startDate.getMinutes());
          }
          else {
            this.reminderInfo.hour = String(startDate.getHours());
            this.reminderInfo.minute = String(startDate.getMinutes());
          }
          this.reminderInfo.duration = String(endDate.getHours() - startDate.getHours());
          if (this.reminderInfo.duration.length === 1) {
            this.reminderInfo.duration = '0' + this.reminderInfo.duration;
          }
        }
        else if (this.state === 'create') {
          this.status = StateOfReminder.create;
          this.reminderInfo.description = '';
          // pre impostare il titolo del promemoria
          // this.reminderInfo.name = 'Titolo del promemoria'
        }
        else {
          this.status = StateOfReminder.edit;
        }
      }
      else {
        this.status = StateOfReminder.create;
      }
      this.isFirstTime = false;
    }
    // this.reminderDone = this.doneFlag;
    if (this.deleteSub) {
      this.deleteFromActionClose();
    }
    if (this.withoutFooter) {
      let date = this.reminderInfoDTO.startDate;
      if (!this.reminderInfoDTO.startDate.includes('/')) {
        this.reminderInfo.date = DateTime.fromJSDate(new Date(date)).toLocal().toFormat('dd/MM/yyyy');
      }
    }
    //   else{
    //     if(this.state === 'view' && this.reminderInfoDTO){
    //       this.reminderInfo.name = this.reminderInfoDTO.name;
    //       this.reminderInfo.description = this.reminderInfoDTO.description;
    //       let startDate: Date = new Date(this.reminderInfoDTO.startDate);
    //       let endDate: Date = new Date(this.reminderInfoDTO.endDate);
    //       this.reminderInfo.date =  DateTime.fromJSDate(startDate).toLocal().toFormat('dd/MM/yyyy');
    //       if (startDate.getHours() < 10) {
    //         this.reminderInfo.hour = '0' + String(startDate.getHours());
    //         this.reminderInfo.minute = String(startDate.getMinutes());
    //       } else {
    //         this.reminderInfo.hour = String(startDate.getHours());
    //         this.reminderInfo.minute = String(startDate.getMinutes());
    //       }
    //       this.reminderInfo.duration = String(endDate.getHours() - startDate.getHours());
    //       if (this.reminderInfo.duration.length === 1) {
    //         this.reminderInfo.duration = '0' + this.reminderInfo.duration;
    //       }
    //       this.state = 'view'
    //   }
    // }
  }
  render() {
    return (h("div", { class: "reminder-container" },
      h("sw-addon-reminder-header", { withoutFooter: this.withoutFooter, addonReminderTitle: this.reminderInfo.name, creationDate: this.reminderInfo.date, state: this.status }),
      h("sw-addon-reminder-body", { withoutFooter: this.withoutFooter, date: this.reminderInfo.date, reminderDoneValue: this.reminderDone, addonReminderInfoFromParent: this.reminderInfo, state: this.status, descriptionText: this.reminderInfo.description }),
      h("sw-addon-reminder-footer", { class: !this.withoutFooter ? 'footer' : 'hidden', reminderDoneProp: this.reminderDone, author: this.userInfo, submitValidation: this.validation, reminderAddonInfo: this.reminderInfo, state: this.status }),
      h("div", { class: { 'badge-error': true, 'hidden': !this.badgeErrorOn } },
        h("sw-badge-error", null))));
  }
  static get is() { return "sw-addon-reminder"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() { return {
    "$": ["sw-addon-reminder.css"]
  }; }
  static get styleUrls() { return {
    "$": ["sw-addon-reminder.css"]
  }; }
  static get properties() { return {
    "sendDataForCalendar": {
      "type": "boolean",
      "mutable": true,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "send-data-for-calendar",
      "reflect": false,
      "defaultValue": "false"
    },
    "withoutFooter": {
      "type": "boolean",
      "mutable": true,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "without-footer",
      "reflect": false,
      "defaultValue": "false"
    },
    "doneFlag": {
      "type": "boolean",
      "mutable": true,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "done-flag",
      "reflect": false
    },
    "deleteSub": {
      "type": "boolean",
      "mutable": true,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "delete-sub",
      "reflect": false,
      "defaultValue": "false"
    },
    "reminderInfoDTO": {
      "type": "unknown",
      "mutable": true,
      "complexType": {
        "original": "ReminderInfoDTO",
        "resolved": "ReminderInfoDTO",
        "references": {
          "ReminderInfoDTO": {
            "location": "import",
            "path": "../../interfaces"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "userInfo": {
      "type": "unknown",
      "mutable": true,
      "complexType": {
        "original": "AuthorStencilDTO",
        "resolved": "AuthorStencilDTO",
        "references": {
          "AuthorStencilDTO": {
            "location": "import",
            "path": "../../interfaces"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "defaultValue": "{name: 'Nome', surname:'Cognome', date:'creato oggi', image:'assets/img/user.svg'}"
    },
    "state": {
      "type": "string",
      "mutable": true,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "state",
      "reflect": false,
      "defaultValue": "''"
    },
    "taskId": {
      "type": "number",
      "mutable": true,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "task-id",
      "reflect": false,
      "defaultValue": "722"
    },
    "idPluginAction": {
      "type": "number",
      "mutable": true,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "id-plugin-action",
      "reflect": false,
      "defaultValue": "9"
    },
    "baseUrl": {
      "type": "string",
      "mutable": true,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "base-url",
      "reflect": false,
      "defaultValue": "'https://app.dev.synbee.it'"
    },
    "idPluginActionExternal": {
      "type": "number",
      "mutable": true,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "id-plugin-action-external",
      "reflect": false,
      "defaultValue": "22"
    }
  }; }
  static get states() { return {
    "badgeErrorOn": {},
    "reminderDone": {},
    "status": {},
    "reminderInfoState": {},
    "reminderInfo": {}
  }; }
  static get events() { return [{
      "method": "undoReminderOutEmitter",
      "name": "undoReminderOutEmitter",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      }
    }, {
      "method": "outputDataEmitter",
      "name": "outputDataEmitter",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }, {
      "method": "deleteAddonReminderEmitter",
      "name": "deleteAddonReminderEmitter",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      }
    }, {
      "method": "collapseReminder",
      "name": "collapseReminder",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      }
    }, {
      "method": "reminderDoneSetter",
      "name": "reminderDoneSetter",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      }
    }, {
      "method": "editOutputDataEmitter",
      "name": "editOutputDataEmitter",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }]; }
  static get watchers() { return [{
      "propName": "deleteSub",
      "methodName": "deleteFromActionClose"
    }, {
      "propName": "state",
      "methodName": "stateDetectionChange"
    }, {
      "propName": "reminderInfo",
      "methodName": "validationOfData"
    }]; }
  static get listeners() { return [{
      "name": "undoReminderEmitter",
      "method": "catchUndoReminder",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "closeReminderEmitter",
      "method": "catchCloseAction",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "createReminderEmitterFromSubmit",
      "method": "sendOutputData",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "editReminderEmitterFromSubmit",
      "method": "editOutputData",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "errorEmitter",
      "method": "catchErrorFromUncomplitedDate",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "reminderDoneEmitter",
      "method": "setReminderDone",
      "target": undefined,
      "capture": true,
      "passive": true
    }, {
      "name": "changeStatusToAddonReminder",
      "method": "changeStat",
      "target": undefined,
      "capture": true,
      "passive": true
    }, {
      "name": "createReminderEmitter",
      "method": "createReminder",
      "target": undefined,
      "capture": true,
      "passive": true
    }, {
      "name": "addonReminderInfoFromBodyEmitter",
      "method": "takeInfoFromBody",
      "target": undefined,
      "capture": true,
      "passive": true
    }, {
      "name": "addonReminderInfoFromHeaderEmitter",
      "method": "takeInfoFromHeder",
      "target": undefined,
      "capture": true,
      "passive": true
    }]; }
}
