import { Host, h, } from "@stencil/core";
import { States } from "src/utils/utils";
import "@ui5/webcomponents/dist/DatePicker.js";
export class SwInspectionForm {
  constructor() {
    this.quarterHours = ["00", "15", "30", "45"];
    this.times = [];
    this.tempArray = [];
    this.status = undefined;
    this.inspectionGetDTO = undefined;
    this.filteredTodos = null;
    this.disableEditModeItems = false;
    this.text = "";
  }
  deleteItem(event) {
    this.inspectionGetDTO = { ...this.inspectionGetDTO };
    this.inspectionGetDTO.inspectionTodos = [
      ...this.inspectionGetDTO.inspectionTodos.filter((el) => el.orderNumber !== event.detail),
    ];
    this.updateInspection.emit(this.inspectionGetDTO);
  }
  rapidDeleteItem(event) {
    this.inspectionGetDTO = { ...this.inspectionGetDTO };
    this.inspectionGetDTO.inspectionTodos = [
      ...this.inspectionGetDTO.inspectionTodos.filter((el) => el.orderNumber !== event.detail),
    ];
    this.updateRapidTodoList.emit(event.detail);
  }
  watchChangeState(newValue) {
    if (newValue === States.view) {
      const list = this.element.shadowRoot.getElementById("sort-list");
      let items = list.getElementsByTagName("sw-checklist-item");
      for (let i of Array.from(items)) {
        i.setAttribute("draggable", "false");
      }
    }
    if (this.element.shadowRoot.getElementById("filter-null")) {
      this.doFilterTodos(null);
    }
  }
  watchDisableEditModeItems(ev) {
    this.disableEditModeItems = ev;
    if (ev === true) {
      const els = this.element.shadowRoot.querySelectorAll("sw-checklist-item");
      els.forEach((el) => {
        el.internalState = States.view;
      });
      this.disableEditModeItems = false;
    }
  }
  componentWillLoad() {
    for (let i = 0; i < 24; i++) {
      i >= 0 && i <= 9
        ? this.times.push("0" + i.toString())
        : this.times.push(i.toString());
    }
  }
  componentShouldUpdate() {
    if (this.inspectionGetDTO != null && this.status !== States.create) {
      if (this.inspectionGetDTO.startDate != null) {
        this.selectedHours =
          this.inspectionGetDTO.startDate instanceof Date
            ? this.inspectionGetDTO.startDate.getHours().toString()
            : new Date(this.inspectionGetDTO.startDate).getHours().toString();
        this.selectedHours = this.addZeroBefore(this.selectedHours);
        this.selectedMinutes =
          this.inspectionGetDTO.startDate instanceof Date
            ? this.inspectionGetDTO.startDate.getMinutes().toString()
            : new Date(this.inspectionGetDTO.startDate).getMinutes().toString();
        this.selectedMinutes = this.addZeroBefore(this.selectedMinutes);
      }
    }
  }
  componentDidLoad() {
    const list = this.element.shadowRoot.getElementById("sort-list");
    const calendar = this.element.shadowRoot.getElementById("myDatepicker2");
    let internalCalendar;
    if (calendar != null) {
      if (calendar.shadowRoot != null) {
        internalCalendar = calendar.shadowRoot.getElementById("ui5wc_1-inner");
        calendar.setAttribute("style", "padding:10px;height:auto;border-radius:0.5rem !important;");
        if (internalCalendar != null) {
          internalCalendar.setAttribute("style", "border: 0px;");
        }
      }
    }
    this.slist(list);
    const dp = this.element.shadowRoot.getElementById("myDatepicker2");
    if (dp !== undefined && dp !== null) {
      dp.addEventListener("change", (e) => {
        this.inspectionGetDTO.startDate = this.convertToDate(e.detail.value);
        if (this.selectedHours !== undefined) {
          this.inspectionGetDTO.startDate.setHours(Number(this.selectedHours));
        }
        if (this.selectedMinutes !== undefined) {
          this.inspectionGetDTO.startDate.setMinutes(Number(this.selectedMinutes));
        }
        this.updateInspection.emit(this.inspectionGetDTO);
      });
    }
  }
  componentDidUpdate() {
    const list = this.element.shadowRoot.getElementById("sort-list");
    this.slist(list);
    const dp = this.element.shadowRoot.getElementById("myDatepicker2");
    if (dp !== undefined && dp !== null) {
      dp.addEventListener("change", (e) => {
        this.inspectionGetDTO.startDate = this.convertToDate(e.detail.value);
        if (this.selectedHours !== undefined) {
          this.inspectionGetDTO.startDate.setHours(Number(this.selectedHours));
        }
        if (this.selectedMinutes !== undefined) {
          this.inspectionGetDTO.startDate.setMinutes(Number(this.selectedMinutes));
        }
        this.updateInspection.emit(this.inspectionGetDTO);
      });
    }
  }
  addItem() {
    this.inspectionGetDTO = { ...this.inspectionGetDTO };
    this.inspectionGetDTO.inspectionTodos.push({
      orderNumber: this.inspectionGetDTO.inspectionTodos.length,
      checked: false,
      description: "",
    });
    this.updateInspection.emit(this.inspectionGetDTO);
  }
  updateCheckedValue(el, ev) {
    el.checked = ev.detail;
  }
  addZeroBefore(n) {
    return (n < 10 ? "0" : "") + n;
  }
  updateOrderArray(arr, fromIndex, toIndex, itemsHtml) {
    const newArr = [...arr];
    newArr.splice(toIndex, 0, newArr.splice(fromIndex, 1)[0]);
    newArr.forEach((todo, index) => {
      todo.orderNumber = index;
    });
    Array.from(itemsHtml).map((item, index) => {
      item.orderNumber = index;
    });
    itemsHtml = [...itemsHtml];
    return newArr;
  }
  convertToDate(dateString) {
    //  Convert a "dd/MM/yyyy" string into a Date object
    let d = dateString.split("/");
    let dat = new Date(d[2] + "/" + d[1] + "/" + d[0]);
    return dat;
  }
  updateState() {
    this.status === States.edit;
    this.updateStatus.emit(this.status);
    this.addItem();
  }
  slist(target) {
    // (A) SET CSS + GET ALL LIST ITEMS
    //target.classList.add("slist");
    let items = target.getElementsByTagName("sw-checklist-item"), current = null;
    // (B) MAKE ITEMS DRAGGABLE + SORTABLE
    for (let i of items) {
      // (B1) ATTACH DRAGGABLE
      if (this.status === States.create || this.status === States.edit) {
        i.draggable = true;
      }
      else {
        i.draggable = false;
      }
      // (B2) DRAG START - YELLOW HIGHLIGHT DROPZONES
      i.ondragstart = () => {
        current = i;
        for (let it of items) {
          if (it != current) {
            it.classList.add("hint");
          }
        }
      };
      // (B3) DRAG ENTER - RED HIGHLIGHT DROPZONE
      i.ondragenter = () => {
        if (i != current) {
          i.classList.add("active");
        }
      };
      // (B4) DRAG LEAVE - REMOVE RED HIGHLIGHT
      i.ondragleave = () => {
        i.classList.remove("active");
      };
      // (B5) DRAG END - REMOVE ALL HIGHLIGHTS
      i.ondragend = () => {
        items = target.querySelectorAll("sw-checklist-item");
        this.tempArray = [
          ...Array.from(items).map((el, i) => {
            el.elementTODO.orderNumber = i;
            return { ...el.elementTODO };
          }),
        ];
        /*  let newIndex = items.indexOf(i);

        this.inspectionGetDTO.inspectionTodos = this.updateOrderArray(
          this.inspectionGetDTO.inspectionTodos,
          i.orderNumber,
          newIndex,
          items
        );
         */
        for (let it of items) {
          it.classList.remove("hint");
          it.classList.remove("active");
        }
        //this.updateTodoList.emit(this.tempArray);
      };
      // (B6) DRAG OVER - PREVENT THE DEFAULT "DROP", SO WE CAN DO OUR OWN
      i.ondragover = (evt) => {
        evt.preventDefault();
      };
      // (B7) ON DROP - DO SOMETHING
      i.ondrop = (evt) => {
        evt.preventDefault();
        if (i != current) {
          let currentpos = 0, droppedpos = 0;
          for (let it = 0; it < items.length; it++) {
            if (current == items[it]) {
              currentpos = it;
            }
            if (i == items[it]) {
              droppedpos = it;
            }
          }
          if (currentpos < droppedpos) {
            i.parentNode.insertBefore(current, i.nextSibling);
          }
          else {
            i.parentNode.insertBefore(current, i);
          }
        }
      };
    }
  }
  handleHours(ev) {
    this.selectedHours = ev.target.value;
    if (this.inspectionGetDTO instanceof Date) {
      this.inspectionGetDTO.startDate.setHours(Number(this.selectedHours));
    }
    else {
      const newDate = new Date(this.inspectionGetDTO.startDate);
      this.inspectionGetDTO.startDate = newDate;
      this.inspectionGetDTO.startDate.setHours(Number(this.selectedHours));
    }
    this.updateInspection.emit(this.inspectionGetDTO);
  }
  handleMinutes(ev) {
    this.selectedMinutes = ev.target.value;
    if (this.inspectionGetDTO instanceof Date) {
      this.inspectionGetDTO.startDate.setMinutes(Number(this.selectedMinutes));
    }
    else {
      const newDate = new Date(this.inspectionGetDTO.startDate);
      this.inspectionGetDTO.startDate = newDate;
      this.inspectionGetDTO.startDate.setMinutes(Number(this.selectedMinutes));
    }
    this.updateInspection.emit(this.inspectionGetDTO);
  }
  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("/");
  }
  doFilterTodos(checked) {
    this.filteredTodos = checked;
    this.inspectionGetDTO = { ...this.inspectionGetDTO };
    this.inspectionGetDTO.inspectionTodos = [
      ...this.inspectionGetDTO.inspectionTodos,
    ];
    this.emitFilteredTodos.emit(this.filteredTodos);
    switch (this.filteredTodos) {
      case true:
        this.element.shadowRoot
          .getElementById("filter-true")
          .classList.add("filter-active");
        this.element.shadowRoot
          .getElementById("filter-false")
          .classList.remove("filter-active");
        this.element.shadowRoot
          .getElementById("filter-null")
          .classList.remove("filter-active");
        break;
      case false:
        this.element.shadowRoot
          .getElementById("filter-false")
          .classList.add("filter-active");
        this.element.shadowRoot
          .getElementById("filter-true")
          .classList.remove("filter-active");
        this.element.shadowRoot
          .getElementById("filter-null")
          .classList.remove("filter-active");
        break;
      default:
        this.element.shadowRoot
          .getElementById("filter-null")
          .classList.add("filter-active");
        this.element.shadowRoot
          .getElementById("filter-true")
          .classList.remove("filter-active");
        this.element.shadowRoot
          .getElementById("filter-false")
          .classList.remove("filter-active");
        break;
    }
  }
  render() {
    var _a, _b, _c, _d, _e, _f, _g;
    let formattedDate;
    if (((_a = this.inspectionGetDTO) === null || _a === void 0 ? void 0 : _a.startDate) instanceof Date) {
      formattedDate =
        this.formatDate((_b = this.inspectionGetDTO) === null || _b === void 0 ? void 0 : _b.startDate) +
          " " +
          this.addZeroBefore((_c = this.inspectionGetDTO) === null || _c === void 0 ? void 0 : _c.startDate.getHours().toString()) +
          ":" +
          this.addZeroBefore((_d = this.inspectionGetDTO) === null || _d === void 0 ? void 0 : _d.startDate.getMinutes().toString());
    }
    else {
      const newDate = new Date((_e = this.inspectionGetDTO) === null || _e === void 0 ? void 0 : _e.startDate);
      formattedDate =
        this.formatDate((_f = this.inspectionGetDTO) === null || _f === void 0 ? void 0 : _f.startDate) +
          " " +
          this.addZeroBefore(newDate.getHours().toString()) +
          ":" +
          this.addZeroBefore(newDate.getMinutes().toString());
    }
    return (h(Host, null, this.status === States.edit || this.status === States.create ? (h("ui5-date-picker", { class: "w-full text-brand-synbee-eolo-v1-06 bg-brand-synbee-eolo-v1-18 mb-2", id: "myDatepicker2", value: this.formatDate(this.inspectionGetDTO.startDate), "format-pattern": "dd/MM/yyyy", placeholder: "Delivery Date..." }, h("div", { slot: "valueStateMessage" }, "The value is not valid. Please provide valid value"))) : (h("div", { class: "flex" }, h("svg", { width: "20", height: "22", viewBox: "0 0 20 22", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, h("path", { d: "M18 2H17V0H15V2H5V0H3V2H2C0.9 2 0 2.9 0 4V20C0 21.1 0.9 22 2 22H18C19.1 22 20 21.1 20 20V4C20 2.9 19.1 2 18 2ZM18 20H2V7H18V20Z", fill: "#6F8DC2" })), h("mds-text", { typography: "detail", class: "ml-2" }, formattedDate))), this.status === States.create || this.status === States.edit ? (h("div", { class: "flex justify-between my-3" }, h("div", { class: "select-wrapper bg-brand-synbee-eolo-v1-18 pr-6" }, h("select", { class: "select-box bg-brand-synbee-eolo-v1-18 pl-5 text-brand-synbee-eolo-v1-06 font-bold", onInput: (event) => this.handleHours(event) }, h("option", { value: "", disabled: true, selected: true, hidden: true }, "Ore"), this.times.map((time) => (h("option", { selected: this.selectedHours === time, value: time }, time))))), h("div", { class: "select-wrapper bg-brand-synbee-eolo-v1-18 pr-6" }, h("select", { class: "select-box bg-brand-synbee-eolo-v1-18 pl-5 text-brand-synbee-eolo-v1-06 font-bold", onInput: (event) => this.handleMinutes(event) }, h("option", { value: "", disabled: true, selected: true, hidden: true }, "Minuti"), this.quarterHours.map((minutes) => (h("option", { selected: this.selectedMinutes === minutes, value: minutes }, minutes))))))) : undefined, h("sw-input-text-area", { state: this.status, text: this.inspectionGetDTO.description, onOutputText: (ev) => {
        this.inspectionGetDTO.description = ev.detail;
        this.updateInspection.emit(this.inspectionGetDTO);
      }, countWords: true }), h("div", { class: "checklist-container" }, h("div", { class: "flex flex-row justify-between items-center" }, h("mds-text", { typography: "h5", class: "text-brand-synbee-eolo-v1-06" }, "Checklist"), this.status === States.view ? (h("div", { class: "flex flex-row justify-between filter-container bg-brand-synbee-eolo-v1-18 items-center" }, h("mds-text", { id: "filter-null", class: "mr-10 cursor-pointer text-brand-synbee-eolo-v1-06 filter-active", typography: "caption", onClick: () => this.doFilterTodos(null) }, "Tutti (", (_g = this.inspectionGetDTO.inspectionTodos) === null || _g === void 0 ? void 0 :
      _g.length, ")"), h("mds-text", { id: "filter-false", class: "cursor-pointer text-brand-synbee-eolo-v1-06", typography: "caption", onClick: () => this.doFilterTodos(false) }, "da completare (", this.inspectionGetDTO.inspectionTodos.filter((el) => el.checked === false).length, ")"), h("mds-text", { id: "filter-true", class: "ml-10 cursor-pointer text-brand-synbee-eolo-v1-06", typography: "caption", onClick: () => this.doFilterTodos(true) }, "Completati (", this.inspectionGetDTO.inspectionTodos.filter((el) => el.checked === true).length, ")"))) : undefined), h("mds-text", { typograghy: "detail", onClick: () => {
        this.status === States.create || this.status === States.edit
          ? this.addItem()
          : this.updateState();
      }, class: "add-checkbox pointer ml-2" }, "Aggiungi checkbox...")), h("ul", { id: "sort-list" }, this.inspectionGetDTO.inspectionTodos.map((el) => {
      if (this.filteredTodos === true && el.checked === true) {
        return (h("sw-checklist-item", { orderNumber: el.orderNumber, onUpdateValue: (ev) => this.updateCheckedValue(el, ev), onSaveItem: (ev) => {
            this.inspectionGetDTO.inspectionTodos = [
              ...this.inspectionGetDTO.inspectionTodos.map((el) => {
                if (el.orderNumber === ev.detail.orderNumber) {
                  el = ev.detail;
                }
                return el;
              }),
            ];
            this.updateTodoList.emit(this.inspectionGetDTO.inspectionTodos);
            this.rapidSaveTodoList.emit(this.inspectionGetDTO);
          }, elementTODO: el, state: this.status }));
      }
      else if (this.filteredTodos === false && el.checked === false) {
        return (h("sw-checklist-item", { orderNumber: el.orderNumber, onUpdateValue: (ev) => this.updateCheckedValue(el, ev), onSaveItem: (ev) => {
            this.inspectionGetDTO.inspectionTodos = [
              ...this.inspectionGetDTO.inspectionTodos.map((el) => {
                if (el.orderNumber === ev.detail.orderNumber) {
                  el = ev.detail;
                }
                return el;
              }),
            ];
            this.updateTodoList.emit(this.inspectionGetDTO.inspectionTodos);
            this.rapidSaveTodoList.emit(this.inspectionGetDTO);
          }, elementTODO: el, state: this.status }));
      }
      else if (this.filteredTodos === null) {
        return (h("sw-checklist-item", { orderNumber: el.orderNumber, onUpdateValue: (ev) => this.updateCheckedValue(el, ev), onSaveItem: (ev) => {
            this.inspectionGetDTO.inspectionTodos = [
              ...this.inspectionGetDTO.inspectionTodos.map((el) => {
                if (el.orderNumber === ev.detail.orderNumber) {
                  el = ev.detail;
                }
                return el;
              }),
            ];
            this.updateTodoList.emit(this.inspectionGetDTO.inspectionTodos);
            this.rapidSaveTodoList.emit(this.inspectionGetDTO);
          }, elementTODO: el, state: this.status }));
      }
    }), h("div", { class: "border-bottom-sort-list" })), h("slot", null)));
  }
  static get is() { return "sw-inspection-form"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["sw-inspection-form.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["sw-inspection-form.css"]
    };
  }
  static get properties() {
    return {
      "status": {
        "type": "string",
        "mutable": true,
        "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": "status",
        "reflect": false
      },
      "inspectionGetDTO": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "InspectionGetDTO",
          "resolved": "InspectionGetDTO",
          "references": {
            "InspectionGetDTO": {
              "location": "import",
              "path": "src/interfaces"
            }
          }
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        }
      },
      "filteredTodos": {
        "type": "boolean",
        "mutable": true,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "filtered-todos",
        "reflect": false,
        "defaultValue": "null"
      },
      "disableEditModeItems": {
        "type": "boolean",
        "mutable": true,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "disable-edit-mode-items",
        "reflect": false,
        "defaultValue": "false"
      }
    };
  }
  static get states() {
    return {
      "text": {}
    };
  }
  static get events() {
    return [{
        "method": "emitFilteredTodos",
        "name": "emitFilteredTodos",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        }
      }, {
        "method": "updateTodoList",
        "name": "updateTodoList",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "ElementTODO[]",
          "resolved": "ElementTODO[]",
          "references": {
            "ElementTODO": {
              "location": "import",
              "path": "src/interfaces"
            }
          }
        }
      }, {
        "method": "rapidSaveTodoList",
        "name": "rapidSaveTodoList",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "InspectionGetDTO",
          "resolved": "InspectionGetDTO",
          "references": {
            "InspectionGetDTO": {
              "location": "import",
              "path": "src/interfaces"
            }
          }
        }
      }, {
        "method": "updateRapidTodoList",
        "name": "updateRapidTodoList",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "number",
          "resolved": "number",
          "references": {}
        }
      }, {
        "method": "updateInspection",
        "name": "updateInspection",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "InspectionGetDTO",
          "resolved": "InspectionGetDTO",
          "references": {
            "InspectionGetDTO": {
              "location": "import",
              "path": "src/interfaces"
            }
          }
        }
      }, {
        "method": "updateStatus",
        "name": "updateStatus",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "States",
          "resolved": "States.create | States.edit | States.view",
          "references": {
            "States": {
              "location": "import",
              "path": "src/utils/utils"
            }
          }
        }
      }];
  }
  static get elementRef() { return "element"; }
  static get watchers() {
    return [{
        "propName": "status",
        "methodName": "watchChangeState"
      }, {
        "propName": "disableEditModeItems",
        "methodName": "watchDisableEditModeItems"
      }];
  }
  static get listeners() {
    return [{
        "name": "deleteItem",
        "method": "deleteItem",
        "target": undefined,
        "capture": false,
        "passive": false
      }, {
        "name": "rapidDeleteItem",
        "method": "rapidDeleteItem",
        "target": undefined,
        "capture": false,
        "passive": false
      }];
  }
}
