import { h, Host, } from "@stencil/core";
import { Actions, States } from "src/utils/utils";
export class SwInspection {
  constructor() {
    this.filterTodosValue = null;
    this.errorMessage = "Errore! Compilare i campi obbligatori";
    this.creationId = Math.floor(Math.random() * 100);
    this.inspectionGetDTO = {
      id: 1,
      name: "",
      description: "",
      startDate: new Date(),
      inspectionTodos: [],
    };
    this._inspectionGetDTO = undefined;
    this.state = States.create;
    this._state = undefined;
    this.baseUrl = "";
    this.idPluginAction = undefined;
    this.idPlugin = undefined;
    this.idTask = undefined;
    this.creationDate = undefined;
    this.editDate = undefined;
    this.actionCreator = undefined;
    this.badgeErrorOn = false;
  }
  checkBadgeErrorOn(newValue) {
    this.badgeErrorOn = newValue;
  }
  createInspection(inspectionGetDTO) {
    const inspectionCreateDTO = {
      name: inspectionGetDTO.name,
      startDate: inspectionGetDTO.startDate,
      description: inspectionGetDTO.description,
      inspectionTodos: inspectionGetDTO.inspectionTodos,
    };
    if (inspectionCreateDTO.name !== "" &&
      inspectionCreateDTO.startDate !== null) {
      fetch(`${this.baseUrl}/services/eolo-api-gateway/external-api/${this.idTask}/${this.idPluginAction}`, {
        method: "POST",
        body: JSON.stringify(inspectionCreateDTO),
        headers: {
          "Content-Type": "application/json",
        },
      })
        .then((res) => {
        this._state = States.view;
        return res.json();
      })
        .then((res) => {
        this.idPlugin = res.id;
        this._inspectionGetDTO = { ...res };
        this._inspectionGetDTO = { ...this._inspectionGetDTO };
      })
        .catch(() => {
        this.errorMessage = "Errore server!!";
        this.badgeErrorOn = true;
      });
    }
    else {
      this.errorMessage = "Errore! Compilare i campi obbligatori";
      this.badgeErrorOn = true;
    }
    setTimeout(() => {
      this.badgeErrorOn = false;
    }, 4000);
  }
  getInspection() {
    fetch(`${this.baseUrl}/services/eolo-api-gateway/external-api/${this.idPluginAction}/${this.idPlugin}`, {
      method: "GET",
    })
      .then((res) => {
      return res.json();
    })
      .then((res) => {
      this.inspectionGetDTO = { ...res };
      this._inspectionGetDTO = { ...res };
      this._inspectionGetDTO.inspectionTodos =
        this._inspectionGetDTO.inspectionTodos.sort((a, b) => a.orderNumber - b.orderNumber);
      this._inspectionGetDTO.startDate = new Date(this._inspectionGetDTO.startDate);
      this._inspectionGetDTO.startDate = this.addHours(this._inspectionGetDTO.startDate, 1);
      this._inspectionGetDTO = { ...this._inspectionGetDTO };
    })
      .catch((err) => {
      console.log(err);
    });
  }
  editInspection(inspectionGetDTO) {
    delete inspectionGetDTO["id"];
    fetch(`${this.baseUrl}/services/eolo-api-gateway/external-api/${this.idPluginAction}/${this.idPlugin}`, {
      method: "PUT",
      body: JSON.stringify(inspectionGetDTO),
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((res) => {
      console.log(res.json());
      this._inspectionGetDTO = { ...inspectionGetDTO };
      this._inspectionGetDTO = { ...this._inspectionGetDTO };
      this._state = States.view;
      /* }  else {
      this._inspectionGetDTO = this.inspectionGetDTO;
      } */
      const el = this.element.shadowRoot.querySelector("sw-inspection-form");
      el.disableEditModeItems = true;
    })
      .catch((err) => {
      console.log(err);
      this.errorMessage = "Errore server!";
      this.badgeErrorOn = true;
    });
    setTimeout(() => {
      this.badgeErrorOn = false;
    }, 4000);
  }
  deleteInspection() {
    fetch(`${this.baseUrl}/services/eolo-api-gateway/external-api/${this.idPluginAction}/${this.idPlugin}`, {
      method: "DELETE",
    }).then(() => {
      //if (res.status === 200) {
      this.emitCancel.emit({ html: this.element });
      // }
    });
  }
  changeState(ev) {
    if (ev.detail.state === "edit") {
      this._state = ev.detail.state;
    }
    else if (ev.detail.mode === "delete" &&
      ev.detail.previousState === States.create) {
      this.emitCancel.emit();
    }
    else if (ev.detail.mode === "delete" &&
      ev.detail.previousState === States.view) {
      this.deleteInspection();
    }
    else if (ev.detail.mode === "delete" &&
      ev.detail.previousState === States.edit) {
      this._state = ev.detail.state;
    }
    this.filterTodosValue = null;
  }
  goToEditState() {
    this._state = States.edit;
  }
  padTo2Digits(num) {
    return num.toString().padStart(2, "0");
  }
  formatDate(date) {
    if (!(date instanceof Date)) {
      date = new Date(date);
    }
    return [
      this.padTo2Digits(date.getDate()),
      this.padTo2Digits(date.getMonth() + 1),
      date.getFullYear(),
    ].join("/");
  }
  componentWillLoad() {
    this._state = this.state;
    if (this._state === States.view) {
      this.getInspection();
    }
    this._inspectionGetDTO = { ...this.inspectionGetDTO };
  }
  addHours(date, hours) {
    date.setHours(date.getHours() + hours);
    return date;
  }
  render() {
    return (h(Host, { id: this.creationId }, h("div", { class: "rounded-md relative" }, h("sw-action-header", { status: this._state, creationDate: this.creationDate, editDate: this.editDate, title: this._inspectionGetDTO.name, onEmitTitle: (ev) => {
        this._inspectionGetDTO.name = ev.detail;
        this._inspectionGetDTO = { ...this._inspectionGetDTO };
      }, onEmitChangeState: (ev) => this.changeState(ev), onEmitCloseAction: () => this.emitCloseAction.emit({ html: this.element }), onEmitDeleteAction: () => this.emitCancel.emit({
        html: this.element,
      }), onEmitInternalCloseAction: (ev) => {
        if (ev.detail) {
          this.element.shadowRoot.querySelector("sw-inspection-form").style.display = "none";
          this.element.shadowRoot.querySelector("sw-action-footer").style.display = "none";
        }
        else {
          this.element.shadowRoot.querySelector("sw-inspection-form").style.display = "block";
          this.element.shadowRoot.querySelector("sw-action-footer").style.display = "block";
        }
      } }), h("sw-inspection-form", { status: this._state, inspectionGetDTO: this._inspectionGetDTO, onEmitFilteredTodos: (ev) => (this.filterTodosValue = ev.detail), onUpdateInspection: (ev) => {
        this._inspectionGetDTO.inspectionTodos = [
          ...this._inspectionGetDTO.inspectionTodos,
        ];
        this._inspectionGetDTO = { ...ev.detail };
      }, onUpdateRapidTodoList: (ev) => {
        this._inspectionGetDTO.inspectionTodos = [
          ...this._inspectionGetDTO.inspectionTodos.filter((el) => el.orderNumber !== ev.detail),
        ];
        this.editInspection(this._inspectionGetDTO);
      }, onRapidSaveTodoList: (ev) => {
        this._inspectionGetDTO = { ...ev.detail };
        this.editInspection(this._inspectionGetDTO);
      }, onUpdateStatus: () => {
        this.goToEditState();
      }, filteredTodos: this.filterTodosValue }), h("sw-action-footer", { status: this._state, class: "rounded-b-md", author: this.actionCreator, onEmitSave: () => {
        switch (this._state) {
          case States.create:
            this.createInspection(this._inspectionGetDTO);
            break;
          case States.edit:
            this.editInspection(this._inspectionGetDTO);
            break;
        }
      }, onEmitCancel: (ev) => {
        if (ev.detail === Actions.delete) {
          this.emitCancel.emit({
            html: this.element,
          });
        }
        if (ev.detail === Actions.cancel) {
          this._state = States.view;
        }
      } }), this.badgeErrorOn === true ? (h("div", { class: {
        "badge-error": true,
        hidden: !this.badgeErrorOn,
        block: this.badgeErrorOn,
      } }, h("sw-badge-error", { class: "error-badge-pos" }))) : undefined)));
  }
  static get is() { return "sw-inspection"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["sw-inspection.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["sw-inspection.css"]
    };
  }
  static get properties() {
    return {
      "creationId": {
        "type": "number",
        "mutable": false,
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "creation-id",
        "reflect": false,
        "defaultValue": "Math.floor(Math.random() * 100)"
      },
      "inspectionGetDTO": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "InspectionGetDTO",
          "resolved": "InspectionGetDTO",
          "references": {
            "InspectionGetDTO": {
              "location": "import",
              "path": "src/interfaces"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "defaultValue": "{\n    id: 1,\n    name: \"\",\n    description: \"\",\n    startDate: new Date(),\n    inspectionTodos: [],\n  }"
      },
      "state": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "States",
          "resolved": "States.create | States.edit | States.view",
          "references": {
            "States": {
              "location": "import",
              "path": "src/utils/utils"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "state",
        "reflect": false,
        "defaultValue": "States.create"
      },
      "baseUrl": {
        "type": "string",
        "mutable": true,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "base-url",
        "reflect": false,
        "defaultValue": "\"\""
      },
      "idPluginAction": {
        "type": "number",
        "mutable": true,
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "id-plugin-action",
        "reflect": false
      },
      "idPlugin": {
        "type": "number",
        "mutable": true,
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "id-plugin",
        "reflect": false
      },
      "idTask": {
        "type": "number",
        "mutable": true,
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "id-task",
        "reflect": false
      },
      "creationDate": {
        "type": "string",
        "mutable": true,
        "complexType": {
          "original": "Date | string",
          "resolved": "Date | string",
          "references": {
            "Date": {
              "location": "global"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "creation-date",
        "reflect": false
      },
      "editDate": {
        "type": "string",
        "mutable": true,
        "complexType": {
          "original": "Date | string",
          "resolved": "Date | string",
          "references": {
            "Date": {
              "location": "global"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "edit-date",
        "reflect": false
      },
      "actionCreator": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "AuthorCreatorDTO",
          "resolved": "AuthorCreatorDTO",
          "references": {
            "AuthorCreatorDTO": {
              "location": "import",
              "path": "src/interfaces"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        }
      }
    };
  }
  static get states() {
    return {
      "_inspectionGetDTO": {},
      "_state": {},
      "badgeErrorOn": {}
    };
  }
  static get events() {
    return [{
        "method": "emitCancel",
        "name": "emitCancel",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "{ html: HTMLElement }",
          "resolved": "{ html: HTMLElement; }",
          "references": {
            "HTMLElement": {
              "location": "global"
            }
          }
        }
      }, {
        "method": "emitCloseAction",
        "name": "emitCloseAction",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "{ html: HTMLElement }",
          "resolved": "{ html: HTMLElement; }",
          "references": {
            "HTMLElement": {
              "location": "global"
            }
          }
        }
      }];
  }
  static get elementRef() { return "element"; }
  static get watchers() {
    return [{
        "propName": "badgeErrorOn",
        "methodName": "checkBadgeErrorOn"
      }];
  }
}
