import { Component, OnInit, Input, ChangeDetectionStrategy } from '@angular/core';
import { OrderItem } from '../../../../core/models/order-item';

@Component({
  selector: 'app-confirmation-item-list',
  templateUrl: './confirmation-item-list.component.html',
  styleUrls: ['./confirmation-item-list.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ConfirmationItemListComponent implements OnInit {
  @Input() displaySelectedOrderItems: OrderItem[] = [];
  @Input() failedItemsIds: { id: number; type: number }[];
  toolTipOpen: { id: number; type: number };
  type = (isDelivery: boolean, isTakeNow: boolean) => (isDelivery ? 3 : isTakeNow ? 1 : 2);
  foundItemFailed = (itemId: number, type: number) => this.failedItemsIds.findIndex((t) => t && t.id === itemId && t.type === type) !== -1;

  constructor() {}

  ngOnInit() {}

  isItemFailed(itemId: number, isDelivery: boolean, isTakeNow: boolean) {
    if (!this.failedItemsIds) {
      return false;
    }
    const type = this.type(isDelivery, isTakeNow);
    const isItemFailed = this.foundItemFailed(itemId, type);
    return isItemFailed;
  }

  isTooltipOpen(itemId: number, isDelivery: boolean, isTakeNow: boolean) {
    if (!this.failedItemsIds) {
      return false;
    }
    const type = this.type(isDelivery, isTakeNow);
    return this.toolTipOpen && this.toolTipOpen.id === itemId && this.toolTipOpen.type === type;
  }

  openTooltip(itemId: number, isDelivery: boolean, isTakeNow: boolean) {
    if (!this.failedItemsIds) {
      return;
    }
    const type = this.type(isDelivery, isTakeNow);
    if (!this.toolTipOpen || !this.foundItemFailed(itemId, type)) {
      this.toolTipOpen = { id: itemId, type: type };
    } else {
      this.closeTooltip();
    }
  }

  closeTooltip() {
    this.toolTipOpen = undefined;
  }
}
