import { Clipboard } from '@angular/cdk/clipboard';
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Router } from '@angular/router';
import { ApplicationService } from '@core/application';
import { DomainPrinterService } from '@domain/printer';
import { DomainTaskCalendarService } from '@domain/task-calendar';
import { PrintModalComponent, PrintModalData } from '@modal/printer';
import { ArticleDTO, DisplayInfoDTO } from '@swagger/eis';
import { UiModalRef, UiModalService } from '@ui/modal';
import { first, map } from 'rxjs/operators';

@Component({
  selector: 'page-article-list-modal',
  templateUrl: 'article-list-modal.component.html',
  styleUrls: ['article-list-modal.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ArticleListModalComponent {
  articles$ = this.domainTaskCalendarService.getArticles({ infoId: this.modalRef.data.id }).pipe(map((response) => response.result));
  expandedArticle: ArticleDTO;

  constructor(
    private modalRef: UiModalRef<any, DisplayInfoDTO>,
    private router: Router,
    private clipboard: Clipboard,
    private domainTaskCalendarService: DomainTaskCalendarService,
    private domainPrinterService: DomainPrinterService,
    private uiModal: UiModalService,
    private _applicationService: ApplicationService
  ) {}

  close() {
    this.modalRef.close();
  }

  async print() {
    const articles = await this.articles$.pipe(first()).toPromise();
    this.uiModal.open({
      content: PrintModalComponent,
      data: {
        printerType: 'Office',
        print: (printer) =>
          this.domainPrinterService.printDisplayInfoDTOArticles({ articles, printer, title: `${this.modalRef.data.title}` }).toPromise(),
      } as PrintModalData,
      config: {
        panelClass: [],
        showScrollbarY: false,
      },
    });
  }

  async eanCopy() {
    const articles = await this.articles$.toPromise();
    const eanString = articles.map((article: ArticleDTO) => article.ean).join(';');
    this.clipboard.copy(eanString);
  }

  async articleSearch() {
    const articles = await this.articles$.toPromise();
    const taskCalendarSearch: string = articles.map((article: ArticleDTO) => article.ean).join(';');
    const lastActivatedProcessId = (
      await this._applicationService.getLastActivatedProcessWithSectionAndType$('customer', 'cart').pipe(first()).toPromise()
    )?.id;

    this.modalRef.close('closeAll');

    if (!lastActivatedProcessId) {
      const processId = Date.now();
      this.router.navigate(['/kunde', processId, 'product', 'search', 'results'], {
        queryParams: { main_qs: taskCalendarSearch },
      });
    } else {
      this.router.navigate(['/kunde', String(lastActivatedProcessId), 'product', 'search', 'results'], {
        queryParams: { main_qs: taskCalendarSearch },
      });
    }
  }
}
