import { r as registerInstance, j as createEvent, h, g as getElement } from './index-aeac5cad.js';
import './App-418c0118.js';
import './_commonjsHelpers-91fffb88.js';
import { N as Notice } from './index-4920b0b3.js';
import './index-66cd4113.js';
import { b as Schedule, C as Connection, I as Item } from './index-df45deab.js';
import { d as dist } from './index-fdd60c34.js';
import { d as dist$4 } from './index-909faba2.js';
import { d as dist$1 } from './index-6b5931f4.js';
import { d as dist$2 } from './index-ff2f9e0e.js';
import { d as dist$3 } from './index-31b724c4.js';

const sv = {
  "Subscription number": "Prenumerationsnummer",
  Advanced: "Avancerat",
  "Create subscription": "Skapa prenumeration",
  "Start date": "Startdatum",
  "End date": "Slutdatum",
  Qty: "Antal",
  Name: "Namn",
  Price: "Pris",
  VAT: "Moms",
  daily: "Daglig",
  weekly: "Veckovis",
  monthly: "Månadsvis",
  quarterly: "Kvartalsvis",
  yearly: "Årlig",
  Day: "Dag",
  "Add item": "Lägg till artikel",
  "Creating subscription...": "Skapar prenumeration...",
  "$0 of $1 subscriptions were created.": "$0 av $1 prenumerationer skapades.",
  "Subscription was created.": "Prenumeration skapades.",
  "Failed to create $0 of $1 subscriptions.": "Kunde inte skapa $0 av $1 prenumerationer.",
  "Failed to create subscription.": "Kunde inte skapa prenumeration.",
};

function create(language) {
  return dist.create({
    sv,
  }, language);
}

const styleCss = ".sc-payfunc-subscription-create-h{display:block;max-width:63em}[hidden].sc-payfunc-subscription-create-h{display:none}smoothly-submit.sc-payfunc-subscription-create{max-width:min-content}.sc-payfunc-subscription-create-h>form.sc-payfunc-subscription-create{display:flex;flex-wrap:wrap;flex-direction:column}.sc-payfunc-subscription-create-h>form.sc-payfunc-subscription-create section.sc-payfunc-subscription-create{display:flex}smoothly-trigger.sc-payfunc-subscription-create{border:none;position:absolute;right:4em;top:1.4em}.sc-payfunc-subscription-create-h>form.sc-payfunc-subscription-create>main.sc-payfunc-subscription-create>content.sc-payfunc-subscription-create>*.sc-payfunc-subscription-create:not(.last):not(span),.sc-payfunc-subscription-create-h>form.sc-payfunc-subscription-create>section.sc-payfunc-subscription-create>*.sc-payfunc-subscription-create:not(smoothly-trigger):not(smoothly-icon){margin-bottom:.7em;margin-left:-1px;flex-grow:1}.sc-payfunc-subscription-create-h>form.sc-payfunc-subscription-create payfunc-select-offset.sc-payfunc-subscription-create,.sc-payfunc-subscription-create-h>form.sc-payfunc-subscription-create payfunc-total-amount.sc-payfunc-subscription-create,.sc-payfunc-subscription-create-h>form.sc-payfunc-subscription-create smoothly-select.sc-payfunc-subscription-create,.sc-payfunc-subscription-create-h>form.sc-payfunc-subscription-create smoothly-input.sc-payfunc-subscription-create{border:1px solid rgb(var(--smoothly-medium-color));border-collapse:collapse}smoothly-select.sc-payfunc-subscription-create{display:grid}.sc-payfunc-subscription-create-h>form.sc-payfunc-subscription-create>section.sc-payfunc-subscription-create>*.sc-payfunc-subscription-create:not(smoothly-select),.sc-payfunc-subscription-create-h>form.sc-payfunc-subscription-create payfunc-total-amount.sc-payfunc-subscription-create{flex-shrink:2}.sc-payfunc-subscription-create-h>form.sc-payfunc-subscription-create>section.sc-payfunc-subscription-create>*.sc-payfunc-subscription-create:first-child{flex-grow:1}.sc-payfunc-subscription-create-h>form.sc-payfunc-subscription-create>main.sc-payfunc-subscription-create{display:flex;flex-direction:row}.sc-payfunc-subscription-create-h>form.sc-payfunc-subscription-create>main.sc-payfunc-subscription-create>content.sc-payfunc-subscription-create{min-width:37em}.sc-payfunc-subscription-create-h>form.sc-payfunc-subscription-create>main.sc-payfunc-subscription-create>content.sc-payfunc-subscription-create>section.sc-payfunc-subscription-create>smoothly-input.sc-payfunc-subscription-create:last-of-type{border-left:none}.sc-payfunc-subscription-create-h>form.sc-payfunc-subscription-create>main.sc-payfunc-subscription-create>content.sc-payfunc-subscription-create>section.sc-payfunc-subscription-create:first-of-type>*.sc-payfunc-subscription-create{display:flex;flex-wrap:nowrap;flex-grow:1}smoothly-icon.opened.sc-payfunc-subscription-create{transform:rotate(90deg);animation-duration:.5s}payfunc-future-due-dates.sc-payfunc-subscription-create{margin-left:.5em;min-width:13em}";

const PayfuncSubscriptionCreate = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.notice = createEvent(this, "notice", 7);
    this.frequency = "monthly";
    this.currency = "SEK";
    this.advanced = false;
    this.itemCount = 0;
    this.itemsVisible = false;
    this.items = [];
  }
  componentWillLoad() {
    this.t = create(this.element);
    this.subscriptionNumber = dist$1.Identifier.generate(4);
    this.calculateSchedule();
  }
  componentDidRender() {
    const divisor = document.getElementById("divisor");
    const start = document.getElementById("start");
    const end = document.getElementById("end");
    const handle = (e) => {
      this.calculateSchedule();
      e.stopPropagation();
      e.preventDefault();
    };
    if (divisor)
      divisor.addEventListener("focusout", handle);
    if (start)
      start.addEventListener("focusout", handle);
    if (end)
      end.addEventListener("focusout", handle);
  }
  submitSubscription(e) {
    const subscription = {
      number: e.detail.number,
      items: this.items.length > 0 ? this.items : dist$2.parse(e.detail.price, "price", this.currency),
      currency: this.currency,
      schedule: {
        frequency: this.frequency,
        divisor: e.detail.divisor ? Schedule.extractDivisor(e.detail.divisor) : undefined,
        offset: this.offset ? Schedule.extractOffset(this.offset, this.frequency) : undefined,
      },
      start: dist$3.Date.is(e.detail.start) ? e.detail.start : undefined,
      end: dist$3.Date.is(e.detail.end) ? e.detail.end : undefined,
    };
    const idArray = Object.keys(this.accounts);
    this.notice.emit(Notice.execute(this.t("Creating subscription..."), async () => {
      let result;
      const response = await Promise.all(idArray.map(id => Connection.post(`account/${id}/subscription`, subscription)));
      const [succeeded, failed] = response.reduce(([s, f], e) => (dist$4.Error.is(e) ? [s, ++f] : [++s, f]), [0, 0]);
      if (succeeded > 0)
        result = [
          true,
          idArray.length > 1
            ? this.t("$0 of $1 subscriptions were created.", succeeded, idArray.length)
            : this.t("Subscription was created."),
        ];
      else
        result = [
          false,
          idArray.length > 1
            ? this.t("Failed to create $0 of $1 subscriptions.", failed, idArray.length)
            : this.t("Failed to create subscription."),
        ];
      return result;
    }));
  }
  calculateSchedule() {
    let divisor, endDate, startDate;
    if (this.advanced) {
      const divisorInput = document.getElementById("divisor");
      divisor = hasValue(divisorInput) ? divisorInput.value : undefined;
    }
    if (document.getElementById("start") && document.getElementById("end")) {
      const start = document.getElementById("start");
      startDate = hasValue(start) && dist$3.DateTime.localize(start.value) ? start.value : dist$3.DateTime.now();
      const end = document.getElementById("end");
      endDate = hasValue(end) ? dist$3.DateTime.localize(end.value) : undefined;
    }
    this.schedule = {
      frequency: this.frequency,
      divisor: divisor ? Schedule.extractDivisor(divisor) : undefined,
      offset: this.offset ? Schedule.extractOffset(this.offset, this.frequency) : undefined,
    };
    this.dueDates = Schedule.calculateDueDates(this.schedule, 5, startDate, endDate);
  }
  onSelectionChanged(e) {
    if (e.detail.identifier == "frequency") {
      this.frequency = e.detail.value;
      this.calculateSchedule();
    }
    if (e.detail.identifier == "currency")
      this.currency = e.detail.value;
  }
  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;
  }
  changeItem(e) {
    e.preventDefault();
    e.stopPropagation();
    this.items[this.items.length - 1] = e.detail;
    this.price = Item.amount(this.items).toFixed(2);
  }
  changeOffset(e) {
    e.preventDefault();
    e.stopPropagation();
    this.offset = e.detail;
    this.calculateSchedule();
  }
  addItem(e) {
    e.preventDefault();
    e.stopPropagation();
    this.items = [...this.items, {}];
    this.price = Item.amount(this.items).toFixed(2);
    this.itemCount++;
    this.itemsVisible = true;
  }
  render() {
    return [
      h("form", null, h("section", null, h("smoothly-input", { type: "text", name: "number", value: this.subscriptionNumber }, this.t("Subscription number")), h("payfunc-total-amount", { price: this.price, itemsvisible: this.itemCount > 1, onAddItem: e => this.addItem(e) }), h("smoothly-select", { identifier: "frequency", background: "transparent" }, Schedule.frequencies.map(option => this.frequency == option ? (h("option", { value: option, selected: true }, this.t(option))) : (h("option", { value: option }, this.t(option))))), h("smoothly-trigger", null, h("smoothly-icon", { toolTip: this.t("Advanced"), onClick: () => (this.advanced = !this.advanced), name: "arrow-forward-circle-outline", fill: "clear", size: "small", color: "medium", class: this.advanced ? "opened" : "" })), h("smoothly-submit", { color: "primary", fill: "clear", prevent: true, onSubmit: (e) => this.submitSubscription(e) }, h("smoothly-icon", { toolTip: this.t("Create subscription"), name: "add-circle", fill: "clear", size: "medium", color: "success" }))), this.advanced
        ? [
          h("section", null, h("payfunc-select-offset", { frequency: this.frequency, onOffsetChanged: e => this.changeOffset(e) }), h("smoothly-input", { type: "divisor", id: "divisor", name: "divisor", value: "0 / 1" }, this.t("Divisor"))),
        ]
        : [], h("main", null, h("content", null, h("section", null, h("smoothly-input", { type: "date", name: "start", id: "start", value: dist$3.DateTime.localize(dist$3.DateTime.parse(dist$3.DateTime.now())).slice(0, 10) }, this.t("Start date")), h("smoothly-input", { type: "date", name: "end", id: "end" }, this.t("End date"))), h("payfunc-item-list", { items: this.items.slice(0, this.items.length - 1), currency: this.currency }), this.itemsVisible ? h("payfunc-item-input", { key: this.itemCount, item: {} }) : []), h("payfunc-future-due-dates", { dates: this.dueDates }))),
    ];
  }
  get element() { return getElement(this); }
};
function hasValue(element) {
  return typeof element.value === "string";
}
PayfuncSubscriptionCreate.style = styleCss;

export { PayfuncSubscriptionCreate as payfunc_subscription_create };
