import * as gracely from "gracely";
import * as model from "@payfunc/model";
export class OrderHandler {
  static async register(callback, client) {
    this.client = client;
    this.callbacks.push(callback);
    callback(this.client, this.orders, this.customerOrders);
    if (!OrderHandler.timer) {
      this.download();
      OrderHandler.timer = setInterval(OrderHandler.download, 5000);
    }
  }
  static async download() {
    var _a;
    if (!this.downloading) {
      try {
        this.downloading = true;
        const response = await ((_a = OrderHandler.client) === null || _a === void 0 ? void 0 : _a.order.list());
        this.downloading = false;
        OrderHandler.orders = gracely.Error.is(response) || typeof response == "string" ? OrderHandler.orders : response;
        if (OrderHandler.orders)
          OrderHandler.customerOrders = OrderHandler.orders.reduce((result, order) => {
            var _a;
            if ((model.Payment.Card.is(order.payment) || model.Payment.Customer.is(order.payment)) &&
              (order.payment.customer || order.customer))
              ((_a = result[typeof order.payment.customer == "string"
                ? order.payment.customer
                : typeof order.customer == "string"
                  ? order.customer
                  : ""]) !== null && _a !== void 0 ? _a : (result[typeof order.payment.customer == "string"
                ? order.payment.customer
                : typeof order.customer == "string"
                  ? order.customer
                  : ""] = [])).push(order);
            return result;
          }, {});
        OrderHandler.callbacks.forEach(callback => callback(OrderHandler.client, OrderHandler.orders, OrderHandler.customerOrders));
      }
      catch (_b) {
        this.downloading = false;
      }
    }
  }
}
OrderHandler.downloading = false;
OrderHandler.customerOrders = {};
OrderHandler.callbacks = [];
