/*!
 * (C) Gasco https://gasco-web-component.herokuapp.com/ - MIT License
 */
import { Fragment } from '@stencil/core';
import { Component, Host, h, Prop, State, Listen, Event } from '@stencil/core';
export class GascoTable {
  constructor() {
    // This can be improved, so that it can be more dynamic.
    this.tableHeader = [{
        name: 'Nombre',
        phone: 'Telefono',
        address: 'Dirección',
        date: 'Fecha',
        hour: 'Hora',
        state: 'Estado'
      }];
    this.pagination = true;
    /**
     * Number of elements to show this taking into account that it will always be 10 + 10.
     */
    this.pageSize = 10;
    /**
     * If it is `1`, `pageSize` will be shown, which is equivalent to the elements that you want to show.
     */
    this.currentPage = 1;
    /**
     * Amounts of items to display, this may vary depending on the user.
     */
    this.suggestionList = [10, 20, 30];
    this.isResponsive = document.documentElement.clientWidth;
    this.checkboxList = [];
    this.stateUserList = [];
    this.isCheckboxAll = false;
    this.isCheckbox = false;
  }
  // EVENT's
  handleResize() {
    this.isResponsive = document.documentElement.clientWidth;
  }
  handleGetTypeAction(ev) {
    const type = ev.detail;
    if (this.checkboxList.length > 0) {
      this.gascoTableAction.emit({ action: type.action, data: this.checkboxList });
    }
    else {
      this.gascoTableAction.emit({ action: type.action, data: type.data });
    }
  }
  componentWillLoad() {
    this.stateUserList = this.users;
  }
  // METHOD's
  handleSelectUser(userOrAll) {
    // We have all the users we want to either edit, delete or etc.
    if (userOrAll === 'all') {
      this.checkboxList = [];
      if (!this.isCheckboxAll) {
        this.users.forEach(({ id }) => this.checkboxList.push(id));
        this.isCheckboxAll = true;
        return 0;
      }
      this.isCheckboxAll = false;
      return 0;
    }
    // We are looking for an existing user.
    const findUser = this.checkboxList.find(id => id === userOrAll);
    if (findUser) {
      // If the user existes we delete it.
      const removeUser = this.checkboxList.filter(id => id !== userOrAll);
      this.checkboxList = removeUser;
    }
    else {
      // If the user does not exist, we save it
      this.checkboxList.push(userOrAll);
      this.isCheckbox = true;
    }
    if (this.checkboxList.length === 0) {
      this.isCheckbox = false;
    }
  }
  handleTableSortData(e) {
    this.stateUserList = [];
    const thead = e.target;
    if (thead.getAttribute("data-dir") === "desc") {
      this.handleSortData(thead.id, "desc");
      thead.setAttribute("data-dir", "asc");
    }
    else {
      this.handleSortData(thead.id, "asc");
      thead.setAttribute("data-dir", "desc");
    }
  }
  handleSortData(param, direction = "asc") {
    const sortedData = direction === "asc"
      ? this.users.sort((a, b) => {
        if (a[param] < b[param]) {
          return -1;
        }
        if (a[param] > b[param]) {
          return 1;
        }
        return 0;
      })
      : this.users.sort((a, b) => {
        if (b[param] < a[param]) {
          return -1;
        }
        if (b[param] > a[param]) {
          return 1;
        }
        return 0;
      });
    this.stateUserList = sortedData;
    // console.log(this.stateUserList);
  }
  renderThead() {
    return this.tableHeader.map(thead => {
      return Object.values(thead).map((value, y) => {
        const valueForSort = Object.keys(thead)[y];
        return (h("gasco-table-col", { id: valueForSort, class: "table-thead", onClick: (e) => this.handleTableSortData(e) },
          value,
          " ",
          h(SvgSort, null)));
      });
    });
  }
  renderTbodyLarger() {
    return this.stateUserList.map((data) => (h("gasco-table-row", null,
      h("gasco-table-col", null,
        h("gasco-checkbox", { checked: this.isCheckboxAll, onClick: () => this.handleSelectUser(data.id) })),
      h("gasco-table-col", null,
        h("gasco-avatar", { src: data.avatar, alt: data.name },
          h("gasco-label", { class: "avatar-label" }, data.name),
          h("gasco-label", { class: "avatar-label" }, data.description))),
      h("gasco-table-col", null, data.phone),
      h("gasco-table-col", null, data.address),
      h("gasco-table-col", null, data.date),
      h("gasco-table-col", null, data.hour),
      h("gasco-table-col", { class: `table-status-${data.state ? 'active' : 'inactive'}` }, data.state ? 'Activo' : 'Inactivo'),
      h("gasco-table-col", { action: true, typeAction: data.id }))));
  }
  renderTbodySmall() {
    return this.stateUserList.map((data) => (h("gasco-table-row", { class: "table-row-small" },
      h("gasco-table-col", { class: "table-col-small" },
        h("gasco-checkbox", { checked: this.isCheckboxAll, onClick: () => this.handleSelectUser(data.id) }),
        h("gasco-avatar", { src: data.avatar, alt: data.name },
          h("gasco-label", { class: "avatar-label" }, data.name),
          h("gasco-label", { class: "avatar-label" }, data.description)),
        h("gasco-table-col", { action: true, typeAction: data.id })),
      h("div", { class: "wrapper-table-small" },
        h("div", { class: "table-small" },
          h("span", null, "Status"),
          h("gasco-table-col", { class: `table-status-${data.state ? 'active' : 'inactive'}` }, data.state ? 'Activo' : 'Inactivo')),
        h("div", { class: "table-small" },
          h("span", null, "Numero"),
          h("gasco-table-col", null, data.phone)),
        h("div", { class: "table-small" },
          h("span", null, "Fecha"),
          h("gasco-table-col", null, data.date)),
        h("div", { class: "table-small" },
          h("span", null, "Direcci\u00F3n"),
          h("gasco-table-col", null, data.address)),
        h("div", { class: "table-small" },
          h("span", null, "Hora"),
          h("gasco-table-col", null, data.hour))))));
  }
  render() {
    const { pagination, currentPage, pageSize, totalItems, suggestionList } = this;
    return (h(Host, { class: {
        'gasco-table': true,
        'gasco-color-primary': true
      } },
      h("div", { role: "table", class: "table-native", part: "native" }, this.isResponsive > 768 ? (h(Fragment, null,
        h("gasco-table-row", { header: true },
          h("gasco-table-col", null,
            h("gasco-checkbox", { onClick: () => this.handleSelectUser('all') })),
          this.renderThead(),
          h("gasco-table-col", { action: this.isCheckboxAll || this.isCheckbox }, !this.isCheckboxAll && !this.isCheckbox && 'Acciones')),
        this.renderTbodyLarger())) : (h(Fragment, null,
        h("gasco-table-row", { header: true, class: "table-row-small" },
          h("gasco-table-col", { class: "table-col-small" },
            h("gasco-checkbox", { onClick: () => this.handleSelectUser('all') })),
          h("gasco-table-col", { action: !this.isCheckboxAll || !this.isCheckbox })),
        this.renderTbodySmall()))),
      pagination && (h("gasco-paginator", { currentPage: currentPage, pageSize: pageSize, totalItems: totalItems, suggestionList: suggestionList }))));
  }
  static get is() { return "gasco-table"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() { return {
    "$": ["gasco-table.scss"]
  }; }
  static get styleUrls() { return {
    "$": ["gasco-table.css"]
  }; }
  static get properties() { return {
    "pagination": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "pagination",
      "reflect": false,
      "defaultValue": "true"
    },
    "totalItems": {
      "type": "number",
      "mutable": false,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": "Taking into account the number of elements to display by default it is `undefined`."
      },
      "attribute": "total-items",
      "reflect": true
    },
    "pageSize": {
      "type": "number",
      "mutable": false,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": "Number of elements to show this taking into account that it will always be 10 + 10."
      },
      "attribute": "page-size",
      "reflect": true,
      "defaultValue": "10"
    },
    "currentPage": {
      "type": "number",
      "mutable": false,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": "If it is `1`, `pageSize` will be shown, which is equivalent to the elements that you want to show."
      },
      "attribute": "current-page",
      "reflect": true,
      "defaultValue": "1"
    },
    "suggestionList": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "number[]",
        "resolved": "number[]",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": "Amounts of items to display, this may vary depending on the user."
      },
      "defaultValue": "[10, 20, 30]"
    },
    "users": {
      "type": "unknown",
      "mutable": true,
      "complexType": {
        "original": "ITableUsers[]",
        "resolved": "ITableUsers[]",
        "references": {
          "ITableUsers": {
            "location": "import",
            "path": "../../interface"
          }
        }
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": "The number of users to display."
      }
    }
  }; }
  static get states() { return {
    "isResponsive": {},
    "checkboxList": {},
    "stateUserList": {},
    "isCheckboxAll": {},
    "isCheckbox": {}
  }; }
  static get events() { return [{
      "method": "gascoTableAction",
      "name": "gascoTableAction",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "ITableColTypeAction",
        "resolved": "ITableColTypeAction",
        "references": {
          "ITableColTypeAction": {
            "location": "import",
            "path": "../../interface"
          }
        }
      }
    }]; }
  static get listeners() { return [{
      "name": "resize",
      "method": "handleResize",
      "target": "window",
      "capture": false,
      "passive": true
    }, {
      "name": "gascoTableTypeAction",
      "method": "handleGetTypeAction",
      "target": "body",
      "capture": false,
      "passive": false
    }]; }
}
const SvgSort = () => (h("svg", { width: "8", height: "14", fill: "none", viewBox: "0 0 8 14", xmlns: "http://www.w3.org/2000/svg" },
  h("path", { d: "M7.33203 9.50007L3.9987 12.8334L0.665364 9.50007M0.665364 4.50007L3.9987 1.16674L7.33203 4.50007", stroke: "#072531", "stroke-width": "1.25", "stroke-linecap": "round", "stroke-linejoin": "round" })));
