import { v4 as uuid } from 'uuid';
import { workerApiUrl } from '@/config/env';

class GetListPayload {
  constructor() {
    this.listData = [];
  }

  pushData(data) {
    this.listData.push(data);
  }

  getList() {
    return this.listData;
  }

  geTotal() {
    return this.listData.length;
  }

  clearList() {
    this.listData = [];
  }
}

class FetchListenerBucket {
  constructor(limit = 100, platform = 'default') {
    this.active = false;
    this.listData = [];
    this.limit = limit;
    this.platform = platform;
  }

  /**
   *
   * @param {string} url
   * @param {object} json
   */
  pushData(url, json) {
    if (!this.active) {
      return false;
    }

    this.listData.push({
      id: uuid(),
      url,
      json,
    });

    if (this.listData.length >= this.limit) {
      this.flushData().catch(() => {});
    }

    return true;
  }

  async flushData() {
    if (!this.active) {
      return false;
    }

    const listenerUrl = `${workerApiUrl}/listener/push`;
    const listData = this.listData.splice(0, this.limit);

    return fetch(listenerUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        platform: this.platform,
        buckets: listData,
      }),
    });
  }

  /**
   *
   * @param {nubmer} limit
   */
  setLimit(limit) {
    this.limit = limit;
  }

  /**
   *
   * @param {boolean} active
   */
  setActive(active) {
    this.active = active;
  }

  clearData() {
    this.listData = [];
  }
}

export const RequestProductPayload = new GetListPayload();
export const RequestSearchPayload = new GetListPayload();
export const RequestShopeeClient = new GetListPayload();

export const FetchListenerBucketShopee = new FetchListenerBucket(100, 'shopee');

export const ShopeeProductStock = new Map();
