import { Ctx as u } from "./accelbyte-widgets33.mjs";
import { Platform as o } from "@accelbyte/sdk-platform";
import { Container as I } from "unstated";
class b extends I {
  constructor(s) {
    super(), this.props = s, this.state = {
      isFetching: !1,
      isSubmitting: !1,
      isClaimingSuccess: !1,
      error: null,
      errorSubmit: null,
      optionboxItem: null,
      itemEntitlementStatus: null
    }, this.sdk = u.getAppState().getSdk();
  }
  async init() {
    await this.fetchOptionboxItem();
  }
  async fetchOptionboxItem() {
    var s, i, e;
    try {
      if (this.state.isFetching || !this.props.selectedOptionbox)
        return;
      await this.setState({
        isFetching: !0,
        optionboxItem: null
      });
      const { selectedOptionbox: t, userId: m } = this.props, c = t == null ? void 0 : t.itemId, a = (s = t.itemSnapshot) == null ? void 0 : s.region;
      if (!a || !c || !m)
        return;
      const r = await o.ItemApi(this.sdk).getLocale_ByItemId(c, { region: a }), l = ((e = (i = r == null ? void 0 : r.optionBoxConfig) == null ? void 0 : i.boxItems) == null ? void 0 : e.map(({ itemId: n }) => n)) || [], h = await o.ItemApi(this.sdk).getItemsLocaleByIds({
        region: a,
        itemIds: l.toString()
      }), p = await o.EntitlementApi(this.sdk).getEntitlementsOwnershipByItemIds_ByUserId(m, {
        ids: l
      }), d = new Map(
        p.filter((n) => !!n.itemId).map((n) => [n.itemId, n])
      );
      this.setState({ itemEntitlementStatus: d, optionboxItem: h });
    } catch (t) {
      this.setState({ error: t });
    } finally {
      this.setState({ isFetching: !1 });
    }
  }
  async claimOptionboxItem(s) {
    try {
      const { userId: i, selectedOptionbox: e } = this.props;
      if (this.state.isSubmitting || !i || !(e != null && e.id))
        return;
      await this.setState({
        isSubmitting: !0
      });
      const t = {
        useCount: 1,
        options: [s]
      };
      await o.EntitlementApi(this.sdk).updateDecrement_ByUserId_ByEntitlementId(i, e.id, t), this.setState({ isClaimingSuccess: !0 });
    } catch (i) {
      this.setState({ errorSubmit: i });
    } finally {
      this.setState({ isSubmitting: !1 });
    }
  }
}
export {
  b as PurchasedOptionboxDialogLogic
};
