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

export class CustomerQueueListManager extends CustomerQueueManager {
  private ticketToQueues(tickets: QueueTicketModel[]): QueueModel[] {
    const ticket = tickets.map((ticket) => {
      const queue = ticket.items.map((item) => {
        return item.queue;
      });

      return queue.flat();
    });

    return ticket.flat().sort((a, b) => b.time - a.time);
  }

  get data() {
    const tickets = this.tickets;
    const ticketItems = {};

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

        ticketItems[item_id] = currentItem
          ? [...currentItem, ticketQueue]
          : [ticketQueue];
      });
    });

    return Object.keys(ticketItems)
      .map((item_id) => {
        const tickets: QueueTicketModel[] = ticketItems[item_id];
        const item = tickets[0].items[0];
        const uniqueTicket = tickets.filter(
          (obj1, i, arr) => arr.findIndex((obj2) => obj2.id === obj1.id) === i,
        );
        let totalQueue = 0;

        const currentTickets = uniqueTicket.map((ticket) => {
          const currentTicket = tickets.filter((t) => t.id === ticket.id);
          const queues = this.ticketToQueues(currentTicket);
          const currentQueues = queues.map((q) => {
            return {
              code: q.code,
              qty: q.qty,
              time: this.toTime(q.time),
              status: q.status,
            };
          });
          totalQueue += currentQueues.length;
          return currentQueues.length > 0
            ? {
                code: ticket.code,
                customer: ticket.customer,
                phone: ticket.phone,
                id: ticket.id,
                queue: currentQueues,
              }
            : null;
        });

        return currentTickets.filter(Boolean).length > 0
          ? {
              id: item.item_id,
              title: item.item.item_queue?.name ?? item.item.name,
              image_url: item.item.image_url,
              qty: totalQueue,
              items: currentTickets.filter(Boolean),
            }
          : null;
      })
      .filter(Boolean);
  }
}
