// Angular Core
import { Component, Input, OnDestroy, OnInit, OnChanges, SimpleChanges } from '@angular/core';
import { Router } from '@angular/router';

// Pipes
import { DetectApostrophePipe } from 'src/app/filters/detect-apostrophe.pipe';

// Services
import { SupplierCatalogService } from 'src/app/services/supplierCatalog/supplier-catalog.service';
import { environment } from 'src/environments/environment';

@Component({
  standalone: false,
  selector: 'app-supplier-details-display',
  templateUrl: './supplier-details-display.component.html',
  styleUrls: ['./supplier-details-display.component.scss'],
})
export class SupplierDetailsDisplayComponent implements OnInit, OnDestroy, OnChanges {
  @Input() supplier!: any;
  @Input() index!: number;
  @Input() estimatedTime!: any;

  flag!: boolean;
  imgUrl: string = environment.imageUrl;
  delayedSupplier: any = null;

  constructor(
    private supplierCatalogService: SupplierCatalogService,
    private detectApostrophe: DetectApostrophePipe,
    private router: Router,
  ) { }

  ngOnInit(): void {}

  ngOnChanges(changes: SimpleChanges) {
    if (changes['supplier']) {
      setTimeout(() => {
        this.delayedSupplier = this.supplier;
      }, 0); // Delay inside child component
    }
  }

  /**
  * Alert flag to set the danger icon if any notification present
  * @param {type} data
  * @returns {Boolean}
  */
  alertFlag(data: object): boolean {
    this.flag = false;
    const storeMessagesArray = Object.keys(data).map(key => ({key, value: (data as any)[key]}));
    storeMessagesArray.forEach((m: {key: string, value: any})=> {
      if(m.value.valid === false){
        this.flag = true;
      }
    })
    return this.flag;
  };

  /**
  * redirect user to supplier search results page with passed values
  */
  supplierCatalogSearch(supplierName: string, supplierId: any) {
    var name = '';
    var Id = supplierId;
    if(this.supplier.supplierData.isDropShipEnabled == true && this.supplier.supplierData.is_prime_supplier == false){
      name = this.detectApostrophe.transform(supplierName.split('-')[0]);
      Id = supplierId.prime_supplier_id;
    } else {
      name = this.detectApostrophe.transform(supplierName);
      Id = supplierId.id;
    }
    this.supplierCatalogService.setSupplierId(Id);
    this.router.navigate(['/market/supplierCatalog'], { queryParams: { supplierName: escape(name), supplierId: Id, mdl: 'mp' } })
  };

  ngOnDestroy(): void {
  }

}
