import { Ctx as h } from "./accelbyte-widgets33.mjs";
import { ItemType as l } from "./accelbyte-widgets185.mjs";
import { Platform as c } from "@accelbyte/sdk-platform";
import { Container as m } from "unstated";
class y extends m {
  constructor(t) {
    super(), this.fetchItemsList = async () => {
      await this.fetchAllItemList({ itemType: l.enum.CODE }).then((s) => {
        this.setState({ codeItems: s });
      });
    }, this.props = t, this.state = {
      isFetching: !1,
      productKeyList: null,
      error: null,
      selectedProductKey: null,
      codeItems: null
    }, this.sdk = h.getAppState().getSdk();
  }
  getLimit() {
    return this.props.pageSize || 10;
  }
  getOffset(t) {
    return t ? (t - 1) * this.getLimit() : 0;
  }
  async init() {
    await this.fetchProductKeys(), await this.fetchItemsList();
  }
  async fetchAllItemList(t) {
    var o;
    let e = !1, n = 0, r = [];
    do {
      let a;
      try {
        const i = await c.ItemApi(this.sdk).getItemsByCriteria({ ...t, offset: n, limit: 100 });
        e = !!((o = i.paging) != null && o.next), n += 100, a = i.data;
      } catch (i) {
        console.error(i), e = !1, a = [];
      }
      r = r.concat(a);
    } while (e);
    return Promise.resolve(r);
  }
  async fetchProductKeys() {
    try {
      if (this.state.isFetching || (await this.setState({
        isFetching: !0,
        productKeyList: null
      }), !this.props.userId))
        return;
      const { userId: t, page: s } = this.props, e = await c.EntitlementApi(this.sdk).getEntitlements_ByUserId(t, {
        offset: this.getOffset(s),
        limit: this.getLimit(),
        entitlementClazz: l.enum.CODE
      });
      this.setState({ productKeyList: e });
    } catch (t) {
      this.setState({ error: t });
    } finally {
      this.setState({ isFetching: !1 });
    }
  }
}
export {
  y as PurchasedKeysLogic
};
