import { Component, Element, Event, h, Listen, Prop, State } from "@stencil/core";
import * as gracely from "gracely";
import { Currency, Language } from "isoly";
import * as tidily from "tidily";
import * as authly from "authly";
import { ClientIdentifier, Notice } from "smoothly";
import { Item, Order, Payment } from "@payfunc/model";
import { PayfuncPortal } from "../index";
import { OrderHandler } from "../OrderHandler";
import * as translation from "./translation";
export class PortalCreateOrder {
  constructor() {
    this.items = [];
    this.itemsVisible = false;
    this.editCounter = 0;
    this.type = "defer";
    this.selected = {};
    this.currency = "SEK";
    this.languages = ["sv", "en"];
    this.language = "sv";
  }
  componentWillLoad() {
    this.orderNumber = authly.Identifier.generate(12);
    this.t = translation.create(this.element);
  }
  async submitCustomerOrder(e) {
    if (this.selected)
      this.submitOrder(Object.values(this.selected)
        .filter((a) => !!a)
        .map(a => ({
        type: "customer",
        customer: a.id,
      })), e.detail.orderNumber, e.detail.price);
  }
  submitDefer(e) {
    const creatablePayment = {
      type: "defer",
      method: this.emailOption ? "email" : "sms",
      contact: this.emailOption ? e.detail.email : e.detail.phone,
      message: e.detail.message,
    };
    this.submitOrder([creatablePayment], e.detail.orderNumber, e.detail.price);
  }
  async submitOrder(payments, orderNumber, price) {
    const styleLinks = document.querySelectorAll("link[rel=stylesheet]");
    let theme = "light";
    styleLinks.forEach(element => {
      if (element.href.startsWith("https://theme.payfunc.com/")) {
        theme = element.href.substring(26);
        theme = theme.substring(0, theme.indexOf("/"));
      }
    });
    const creatableOrder = {
      client: ClientIdentifier.value,
      items: this.items && this.items.length > 0 ? this.items : tidily.parse(price, "price", this.currency),
      currency: this.currency,
      theme,
      language: this.language,
    };
    this.notice.emit(Notice.execute(payments.length > 1 ? this.t("Creating orders...") : this.t("Creating order..."), async () => {
      let result;
      const response = await Promise.all(payments.map(payment => {
        var _a;
        return creatableOrder.items
          ? (_a = PayfuncPortal.client) === null || _a === void 0 ? void 0 : _a.order.create(Object.assign(Object.assign({}, creatableOrder), { items: creatableOrder.items, number: orderNumber !== null && orderNumber !== void 0 ? orderNumber : authly.Identifier.generate(12), payment, customer: Payment.Customer.Creatable.is(payment) ? payment.customer : undefined }))
          : gracely.server.backendFailure();
      }));
      const [succeeded, failed, pended] = response.reduce(([s, f, p], e) => {
        var _a;
        return gracely.Error.is(e)
          ? [s, ++f, p]
          : Order.is(e) && (Array.isArray(e.status) ? e.status.includes("pending") : (_a = e === null || e === void 0 ? void 0 : e.status) === null || _a === void 0 ? void 0 : _a.pending)
            ? [s, f, ++p]
            : [++s, f, p];
      }, [0, 0, 0]);
      if (failed > 0) {
        result = [
          false,
          payments.length > 1
            ? this.t("Failed to create $0 of $1 orders.", failed, payments.length)
            : this.t("Failed to create order."),
        ];
      }
      else if (pended > 0)
        result = [
          false,
          payments.length > 1
            ? this.t("$0 of $1 payments were declined.", pended, payments.length)
            : this.t("Payment was declined."),
        ];
      else {
        await OrderHandler.download();
        result = [
          true,
          payments.length > 1
            ? this.t("$0 of $1 orders were created.", succeeded, payments.length)
            : this.t("Order was created."),
        ];
        const form = document.getElementsByName("defer");
        if (form.length > 0) {
          const smoothlyInputs = form[0].getElementsByTagName("smoothly-input");
          for (let i = 0; i < smoothlyInputs.length; i++) {
            const element = smoothlyInputs.item(i);
            if (hasValue(element))
              element.value = "";
          }
        }
        this.reset();
        this.orderNumber = authly.Identifier.generate(12);
      }
      return result;
    }));
  }
  handleItemCleared(e) {
    e.stopPropagation();
    e.preventDefault();
    this.price = Item.amount(this.items).toFixed(2);
    if (this.items.length < 2)
      this.reset();
  }
  reset() {
    this.items = [];
    this.itemsVisible = false;
    this.price = "";
  }
  changeItem(e) {
    e.preventDefault();
    e.stopPropagation();
    this.items[this.items.length - 1] = e.detail;
    this.price = Item.amount(this.items).toFixed(2);
  }
  deleteItem(e) {
    const items = [];
    this.price = (Number(this.price) - Item.amount(this.items[e.detail.index])).toFixed(2);
    for (let i = 0; i < this.items.length; i++)
      if (i != e.detail.index) {
        items.push(this.items[i]);
      }
    this.items = items;
  }
  addItem(e) {
    e.preventDefault();
    e.stopPropagation();
    this.items = [...this.items, {}];
    this.itemsVisible = true;
    this.price = Item.amount(this.items).toFixed(2);
    this.editCounter++;
  }
  onSelectionChanged(e) {
    if (e.detail.identifier == "currency" && Currency.is(e.detail.value))
      this.currency = e.detail.value;
    else if (e.detail.identifier == "language" && Language.is(e.detail.value))
      this.language = e.detail.value;
  }
  render() {
    const t = this.t;
    return [
      h("form", { name: "defer" },
        this.type == "defer" || (this.selected && Object.keys(this.selected).length == 1) ? (h("section", null,
          h("smoothly-input", { class: "left slim", type: "text", name: "orderNumber", value: this.orderNumber }, t("Order number")))) : (""),
        h("section", { id: "languageBox" },
          h("smoothly-select", { identifier: "language", background: "transparent" }, this.languages.map(option => this.language == option ? (h("option", { value: option, selected: true }, option)) : (h("option", { value: option }, option))))),
        h("section", null,
          h("ig-total-amount", { price: this.price, itemsvisible: this.itemsVisible, onAddItem: (e) => this.addItem(e) })),
        this.type == "defer" ? (h("section", { id: "receiver" }, this.emailOption ? (h("smoothly-input", { type: "text", name: "email" }, t("Email"))) : (h("smoothly-input", { type: "phone", name: "phone" }, t("Phone"))))) : (""),
        h("smoothly-submit", { color: "primary", fill: "clear", prevent: true, onSubmit: (e) => (this.type == "defer" ? this.submitDefer(e) : this.submitCustomerOrder(e)) },
          h("smoothly-icon", { toolTip: t("Create order"), name: "send", fill: "clear", size: "medium", color: "success" })),
        this.emailOption || this.type == "customer" ? (h("section", { id: "message" },
          h("smoothly-input", { type: "text", name: "message" }, t("Message")))) : ([]),
        h("ig-item-list", { items: this.items.slice(0, this.items.length - 1), currency: this.currency }),
        this.itemsVisible ? h("ig-item-input", { key: this.editCounter, item: {} }) : ""),
    ];
  }
  static get is() { return "portal-create-order"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() { return {
    "$": ["style.css"]
  }; }
  static get styleUrls() { return {
    "$": ["style.css"]
  }; }
  static get properties() { return {
    "emailOption": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "email-option",
      "reflect": false
    },
    "orders": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Order[]",
        "resolved": "Order[] | undefined",
        "references": {
          "Order": {
            "location": "import",
            "path": "@payfunc/model"
          }
        }
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "type": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "Payment.Type",
        "resolved": "\"card\" | \"customer\" | \"defer\" | \"direct\" | \"installment\" | \"invoice\" | \"swish\"",
        "references": {
          "Payment": {
            "location": "import",
            "path": "@payfunc/model"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "type",
      "reflect": false,
      "defaultValue": "\"defer\""
    },
    "selected": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "{ [id: string]: Customer | undefined }",
        "resolved": "undefined | { [id: string]: Customer | undefined; }",
        "references": {
          "Customer": {
            "location": "import",
            "path": "@payfunc/model"
          }
        }
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "defaultValue": "{}"
    },
    "currency": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "Currency",
        "resolved": "\"AED\" | \"AFN\" | \"ALL\" | \"AMD\" | \"ANG\" | \"AOA\" | \"ARS\" | \"AUD\" | \"AWG\" | \"AZN\" | \"BAM\" | \"BBD\" | \"BDT\" | \"BGN\" | \"BHD\" | \"BIF\" | \"BMD\" | \"BND\" | \"BOB\" | \"BOV\" | \"BRL\" | \"BSD\" | \"BTN\" | \"BWP\" | \"BYN\" | \"BZD\" | \"CAD\" | \"CDF\" | \"CHE\" | \"CHF\" | \"CHW\" | \"CLF\" | \"CLP\" | \"CNY\" | \"COP\" | \"COU\" | \"CRC\" | \"CUC\" | \"CUP\" | \"CVE\" | \"CZK\" | \"DJF\" | \"DKK\" | \"DOP\" | \"DZD\" | \"EGP\" | \"ERN\" | \"ETB\" | \"EUR\" | \"FJD\" | \"FKP\" | \"GBP\" | \"GEL\" | \"GHS\" | \"GIP\" | \"GMD\" | \"GNF\" | \"GTQ\" | \"GYD\" | \"HKD\" | \"HNL\" | \"HRK\" | \"HTG\" | \"HUF\" | \"IDR\" | \"ILS\" | \"INR\" | \"IQD\" | \"IRR\" | \"ISK\" | \"JMD\" | \"JOD\" | \"JPY\" | \"KES\" | \"KGS\" | \"KHR\" | \"KMF\" | \"KPW\" | \"KRW\" | \"KWD\" | \"KYD\" | \"KZT\" | \"LAK\" | \"LBP\" | \"LKR\" | \"LRD\" | \"LSL\" | \"LYD\" | \"MAD\" | \"MDL\" | \"MGA\" | \"MKD\" | \"MMK\" | \"MNT\" | \"MOP\" | \"MRU\" | \"MUR\" | \"MVR\" | \"MWK\" | \"MXN\" | \"MXV\" | \"MYR\" | \"MZN\" | \"NAD\" | \"NGN\" | \"NIO\" | \"NOK\" | \"NPR\" | \"NZD\" | \"OMR\" | \"PAB\" | \"PEN\" | \"PGK\" | \"PHP\" | \"PKR\" | \"PLN\" | \"PYG\" | \"QAR\" | \"RON\" | \"RSD\" | \"RUB\" | \"RWF\" | \"SAR\" | \"SBD\" | \"SCR\" | \"SDG\" | \"SEK\" | \"SGD\" | \"SHP\" | \"SLL\" | \"SOS\" | \"SRD\" | \"SSP\" | \"STN\" | \"SVC\" | \"SYP\" | \"SZL\" | \"THB\" | \"TJS\" | \"TMT\" | \"TND\" | \"TOP\" | \"TRY\" | \"TTD\" | \"TWD\" | \"TZS\" | \"UAH\" | \"UGX\" | \"USD\" | \"USN\" | \"UYI\" | \"UYU\" | \"UYW\" | \"UZS\" | \"VES\" | \"VND\" | \"VUV\" | \"WST\" | \"XAF\" | \"XAG\" | \"XAU\" | \"XBA\" | \"XBB\" | \"XBC\" | \"XBD\" | \"XCD\" | \"XDR\" | \"XOF\" | \"XPD\" | \"XPF\" | \"XPT\" | \"XSU\" | \"XTS\" | \"XUA\" | \"XXX\" | \"YER\" | \"ZAR\" | \"ZMW\" | \"ZWL\"",
        "references": {
          "Currency": {
            "location": "import",
            "path": "isoly"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "currency",
      "reflect": false,
      "defaultValue": "\"SEK\""
    }
  }; }
  static get states() { return {
    "t": {},
    "items": {},
    "price": {},
    "itemsVisible": {},
    "editCounter": {},
    "language": {}
  }; }
  static get events() { return [{
      "method": "notice",
      "name": "notice",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "Notice",
        "resolved": "Notice",
        "references": {
          "Notice": {
            "location": "import",
            "path": "smoothly"
          }
        }
      }
    }]; }
  static get elementRef() { return "element"; }
  static get listeners() { return [{
      "name": "itemCleared",
      "method": "handleItemCleared",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "itemChanged",
      "method": "changeItem",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "itemDeleted",
      "method": "deleteItem",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "selectionChanged",
      "method": "onSelectionChanged",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
function hasValue(element) {
  return typeof element === "object" && typeof element.value === "string";
}
