import { Ctx as m } from "./accelbyte-widgets33.mjs";
import { PendingOrdersAppManager as d } from "./accelbyte-widgets451.mjs";
import { Container as g } from "unstated";
import { Platform as n, OrderStatus as u } from "@accelbyte/sdk-platform";
class f extends g {
  constructor(s) {
    super(), this.orderExpiredTimeout = async () => {
      const { order: t } = this.state;
      if (!t || !t.expireTime)
        return;
      const e = new Date().getTime(), i = new Date(t.expireTime).getTime() - e;
      setTimeout(() => {
        this.setState({ orderIsExpired: !0 });
      }, i);
    }, this.fetchOrder = async (t) => {
      const { userId: e } = this.props;
      try {
        if (!e || !t)
          return;
        const r = await n.OrderApi(this.sdk).getOrder_ByUserId_ByOrderNo(e, t);
        this.setState({ order: r });
      } catch (r) {
        this.setState({ error: r });
      }
    }, this.cancelAllOrders = () => {
      var t;
      return (t = this.pendingOrdersAppManager) == null ? void 0 : t.cancelAll();
    }, this.props = s, this.state = {
      isFetching: !1,
      error: null,
      order: null,
      orderIsExpired: !1,
      item: null,
      ...d.DEFAULT_STATE
    }, this.sdk = m.getAppState().getSdk();
  }
  async init() {
    const { userId: s, orderNo: t } = this.props;
    try {
      if (this.state.isFetching)
        return;
      this.setState({
        isFetching: !0,
        error: null,
        order: null
      });
      const e = await n.OrderApi(this.sdk).getOrder_ByUserId_ByOrderNo(s, t), r = await n.ItemApi(this.sdk).getItemsLocaleByIds({
        itemIds: e == null ? void 0 : e.itemId
      }), [i] = r;
      this.pendingOrdersAppManager = new d(this.sdk, {
        userId: this.props.userId,
        itemId: e.itemId
      }), this.pendingOrdersAppManager.subscribe(() => {
        const c = Object.keys(d.DEFAULT_STATE).reduce(
          (o, p) => {
            var h;
            return o[p] = (h = this.pendingOrdersAppManager) == null ? void 0 : h.state[p], o;
          },
          {}
        );
        this.setState(c);
      }), await this.pendingOrdersAppManager.init();
      const { fetchOrdersError: a } = this.pendingOrdersAppManager.state;
      if (a)
        throw a;
      await this.setState({ order: e, item: i });
    } catch (e) {
      this.setState({ error: e });
    } finally {
      await this.setState({ isFetching: !1 }), this.state.order && this.state.order.status === u.enum.INIT && this.orderExpiredTimeout();
    }
  }
}
export {
  f as OrderLogic
};
