import {
  QueueItemModel,
  QueueModel,
} from 'src/modules/queue/data/models/queue.model';
import { CustomerQueueManager } from './customer-queue.manager';
import { QueueCondition } from '../formula/queue-condition.formula';

export class CustomerQueueItemListManager extends CustomerQueueManager {
  protected queues: QueueModel[] = [];
  currentQueues(queues: QueueModel[]) {
    this.queues = queues;
  }
  get data() {
    const tickets = this.tickets;
    const ticketCount = {};
    const queueCondition = new QueueCondition(this.queues);

    const ticketItems = {};
    tickets.forEach((ticket) => {
      const itemsInTicket = [];
      ticket.items.forEach((item) => {
        const item_id = item.item.item_queue?.id ?? item.item.id;
        const currentItem = ticketItems[item_id];
        ticketItems[item_id] = currentItem ? [...currentItem, item] : [item];
        itemsInTicket.push(item_id);
      });

      const uniqueTicket = Array.from(new Set(itemsInTicket));

      uniqueTicket.forEach((item_id) => {
        ticketCount[item_id] = ticketCount[item_id]
          ? ticketCount[item_id] + 1
          : 1;
      });
    });

    return Object.values<QueueItemModel[]>(ticketItems).map((items) => {
      const item = items[0];
      const item_qty = items.reduce((acc, item) => acc + item.qty, 0);
      const queue_qty = this.queueItemQty(items);
      const queueItem = item.item.item_queue ?? item.item;
      return {
        id: queueItem.id,
        queue_item_id: item.id,
        title: queueItem.name,
        image_url: item.item.image_url,
        qty: item_qty - queue_qty,
        ticket: ticketCount[queueItem.id],

        queue_condition: queueCondition.condition(queueItem.id),
        ...queueCondition.condition(queueItem.id),
      };
    });
  }

  protected queueItemQty(queues: QueueItemModel[]) {
    return queues.reduce(
      (acc, item) => acc + item.queue.reduce((acc, q) => acc + q.qty, 0),
      0,
    );
  }
}
