import { Component, Element, Event, h, Host, Prop, State } from "@stencil/core";
import * as isoly from "isoly";
import { Notice } from "smoothly";
import { Frequency, Item, Schedule, Subscription } from "@payfunc/model";
import { Handler } from "../Handler";
import * as translation from "./translation";
export class CustomerSubscriptionsPanel {
  constructor() {
    this.detailedScheduleText = true;
  }
  componentWillLoad() {
    this.t = translation.create(this.element);
    this.updateDueDates();
  }
  updateDueDates() {
    var _a;
    const dueDates = [];
    let date = (_a = this.subscription.due) !== null && _a !== void 0 ? _a : this.subscription.start;
    for (let i = 0; i < 5; i++) {
      date = Schedule.next(this.subscription.schedule, date);
      if (date && (!this.subscription.end || date < this.subscription.end))
        dueDates.push(date);
    }
    this.dueDates = dueDates;
  }
  cancel() {
    this.notice.emit(Notice.execute(this.t("Cancelling subscription..."), async () => {
      const response = await Handler.client.customer.cancelSubscription("me", this.subscription.id);
      let result;
      if (Array.isArray(response) && response.every(Subscription.is)) {
        const subscription = response.find(s => this.subscription.id == s.id);
        if (subscription) {
          this.subscription = subscription;
          this.updateDueDates();
          if (subscription.end && subscription.end <= isoly.DateTime.now().substring(0, 10))
            result = [true, this.t("Subscription was cancelled.")];
        }
      }
      return !result ? [false, this.t("Failed to cancel subscription.")] : result;
    }));
  }
  scheduleTranslation(schedule, short) {
    const t = this.t;
    let result = Schedule.toString(schedule, short);
    result = this.translateHelper(result, "to last");
    result = this.translateHelper(result, "starting from the");
    result = this.translateHelper(result, "starting from");
    result = t("onThe", "doesTranslationExist") != "onThe" ? t("onThe", result) : result;
    result = this.translateHelper(result, "on the");
    const wordSplit = result.split(" ");
    result = wordSplit.reduce((r, c) => {
      const ordinalsTranslation = t("ordinals", c);
      return (!r ? "" : r + " ") + t(ordinalsTranslation != "ordinals" ? ordinalsTranslation : c);
    }, "");
    return result;
  }
  translateHelper(input, translateString) {
    const t = this.t;
    const translated = t(translateString);
    if (input.split(translateString).length > 0) {
      const splitted = input.split(translateString);
      input = splitted.join(translated);
    }
    return input;
  }
  getCustomCssVariables() {
    var _a, _b, _c, _d, _e, _f;
    const result = {};
    if (this.cosmetic && (typeof this.cosmetic == "object" || ((_a = this.cosmetic) === null || _a === void 0 ? void 0 : _a.length) > 0)) {
      const cosmetic = typeof this.cosmetic == "string" && this.cosmetic.length > 0 ? JSON.parse(this.cosmetic) : this.cosmetic;
      Object.entries({
        "--smoothly-font-family": (_b = cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.fontFamily) !== null && _b !== void 0 ? _b : cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.font_family,
        "--smoothly-dark-contrast": (_c = cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.body) === null || _c === void 0 ? void 0 : _c.color,
        "--smoothly-dark-color": (_d = cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.body) === null || _d === void 0 ? void 0 : _d.background,
        "--smoothly-light-color": (_e = cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.header) === null || _e === void 0 ? void 0 : _e.background,
        "--smoothly-light-contrast": (_f = cosmetic === null || cosmetic === void 0 ? void 0 : cosmetic.header) === null || _f === void 0 ? void 0 : _f.color,
      }).forEach(([key, value]) => {
        value && (result[key] = value);
      });
    }
    return result;
  }
  render() {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    const t = this.t;
    return (h(Host, { style: this.getCustomCssVariables() },
      h("h2", { color: "light" },
        t(Frequency.is(this.subscription.schedule) ? this.subscription.schedule : this.subscription.schedule.frequency),
        " ",
        t("Subscription"),
        this.subscription.end && this.subscription.end <= isoly.Date.now() ? ("") : (h("smoothly-icon", { name: "trash", size: "small", fill: "clear", color: "dark", toolTip: t("Cancel subscription"), onClick: () => this.cancel() }))),
      h("section", { color: "dark" },
        h("column", null,
          h("row", null,
            h("h1", null,
              t("Start"),
              ":"),
            h("smoothly-display", { type: "text", value: (_a = this.subscription.start.substring(0, 10)) !== null && _a !== void 0 ? _a : t("Unknown date") })),
          h("row", null,
            h("h1", null,
              t("End"),
              ":"),
            h("smoothly-display", { type: "text", value: (_c = (_b = this.subscription.end) === null || _b === void 0 ? void 0 : _b.substring(0, 10)) !== null && _c !== void 0 ? _c : t("Ongoing") })),
          h("row", null,
            h("h1", null,
              t("Schedule"),
              ":"),
            h("smoothly-display", { class: "pointer", type: "text", onClick: () => (this.detailedScheduleText = !this.detailedScheduleText), value: (_d = this.scheduleTranslation(this.subscription.schedule, this.detailedScheduleText)) !== null && _d !== void 0 ? _d : t("Invalid Schedule") })),
          h("row", null,
            h("column", null,
              h("row", null,
                h("h1", null,
                  t("Next Payment"),
                  ":"),
                h("smoothly-display", { type: "text", value: (_f = (_e = this.subscription.due) === null || _e === void 0 ? void 0 : _e.substring(0, 10)) !== null && _f !== void 0 ? _f : t("None") })),
              h("row", { class: "middle" },
                h("h1", null,
                  t("Amount"),
                  ":"),
                h("smoothly-display-amount", { amount: Item.amount(this.subscription.items).toString(), currency: this.subscription.currency }))))),
        h("column", null,
          h("row", { class: "third" },
            h("h1", null,
              t("Number"),
              ":"),
            h("smoothly-display", { type: "text", value: (_g = this.subscription.number) !== null && _g !== void 0 ? _g : this.subscription.id })),
          h("row", { class: "third" }, ((_h = this.dueDates) === null || _h === void 0 ? void 0 : _h.length) > 0 ? h("ig-future-due-dates", { dates: this.dueDates }) : "")))));
  }
  static get is() { return "customer-subscriptions-panel"; }
  static get encapsulation() { return "scoped"; }
  static get originalStyleUrls() { return {
    "$": ["style.css"]
  }; }
  static get styleUrls() { return {
    "$": ["style.css"]
  }; }
  static get properties() { return {
    "subscription": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Subscription",
        "resolved": "Subscription",
        "references": {
          "Subscription": {
            "location": "import",
            "path": "@payfunc/model"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "orders": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Order[]",
        "resolved": "Order[]",
        "references": {
          "Order": {
            "location": "import",
            "path": "@payfunc/model"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "receipt": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean | undefined",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "receipt",
      "reflect": false
    },
    "cosmetic": {
      "type": "string",
      "mutable": true,
      "complexType": {
        "original": "| string\n\t\t| {\n\t\t\t\tfontFamily?: string\n\t\t\t\theader?: { background?: string; color?: string }\n\t\t\t\tbody?: { background?: string; color?: string }\n\t\t\t\tsuccess?: { background?: string; color?: string }\n\t\t  }",
        "resolved": "string | undefined | { fontFamily?: string | undefined; header?: { background?: string | undefined; color?: string | undefined; } | undefined; body?: { background?: string | undefined; color?: string | undefined; } | undefined; success?: { background?: string | undefined; color?: string | undefined; } | undefined; }",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "cosmetic",
      "reflect": false
    }
  }; }
  static get states() { return {
    "dueDates": {},
    "detailedScheduleText": {},
    "t": {}
  }; }
  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"; }
}
