// Angular Core
import { Component, Input, OnInit } from '@angular/core';

// RxJs
import { catchError, throwError } from 'rxjs';

// Components
import { LoadingmodalComponent } from 'src/app/components/loadingmodal/loadingmodal.component';

// Models
import { WrittenmodalComponent } from '../../../writtenmodal/writtenmodal.component';

// Services
import { SearchService } from 'src/app/services/search/search.service';

// Thired Party
import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import HelloSign from 'hellosign-embedded';

@Component({
  standalone: false,
  selector: 'app-firstordernotice',
  templateUrl: './firstordernotice.component.html',
  styleUrls: ['./firstordernotice.component.scss']
})
export class FirstordernoticeComponent implements OnInit {
  @Input() firstOrderNoticeSupp!: number[];
  @Input() firstOrderSuppSignType!: any[];
  @Input() reviewOrderPopup!: NgbModalRef;
  @Input() firstOrderPopup!: NgbModalRef;
  @Input() cartConfirmationPopup!: NgbModalRef;


  constructor(
    private modalService: NgbModal,
    private searchService:SearchService
  ) { }

  hellosign = {
      url: '',
      client_id: '',
      message: ''
  };


  ngOnInit(): void {
  }

  /**
   * Method introduced as part of TRX-8437
   * Method sendCreditAppDoc to Buyers while sending the app to Buyers in the background,
   * this method will display loading... icon in the modal popup.
   *
   * @param array supplierIds
   * @returns void
  */
  loadingPopup!: NgbModalRef
  lastSupId!: any
  firstOrderNoticeApply(supplierIds: number[]) {
    this.loadingPopup = this.modalService.open(LoadingmodalComponent, {size: 'sm'});
    this.lastSupId = supplierIds[supplierIds.length - 1];
    supplierIds.forEach((supplierId: number) => {
          var args: {supplier_id: number, document_name: string} = {
              'supplier_id': supplierId,
              'document_name': 'SupplierDocument'
          };
          if(this.firstOrderSuppSignType[supplierId] === "WRITTEN") {
              this.sendCreditApp(args);
          } else if (this.lastSupId === supplierId){
              this.getHSForm(args);
          }
      });
  };

  /**
   * Method introduced as part of TRX-8437
   * Sends Supplier Credit Application document to Buyer
   * and displays "Check your Email" popup after email sent successfully to Buyers.
   *
   * @param array args
   *
   * @return void
  */
  fromCart: boolean = false
  buyerEmail: string = ""
  writtenPopup!: NgbModalRef;
  sendCreditApp(args: {supplier_id: number, document_name: string}) {
    var r = this.searchService.callDocument(args)
    .pipe(
      catchError(() => {
        return throwError(() => new Error('ups sommething happend'));
      })
    )
    .subscribe({
      next: (response) => {
        if(response.data.buyerEmail && this.lastSupId === args.supplier_id) {
            var row :{supplierName: string, buyerEmail: string} = {
              supplierName : response.data.supplierName,
              buyerEmail : response.data.buyerEmail
            };
            this.fromCart = true;
            this.buyerEmail = response.data.buyerEmail;
            this.loadingPopup.close();
            this.writtenPopup = this.modalService.open(WrittenmodalComponent, {size: 'sm'});
            this.writtenPopup.componentInstance.row = row;
            this.writtenPopup.componentInstance.title = "CHECK YOUR EMAIL";
            this.writtenPopup.componentInstance.writtenModal = this.writtenPopup;
            this.writtenPopup.componentInstance.writtenClickOk = () => {
                if (this.writtenPopup) {
                  this.writtenPopup.close();
                }
                if (this.reviewOrderPopup) {
                  this.reviewOrderPopup.close('Confirm');
                }
                if (this.firstOrderPopup) {
                  this.firstOrderPopup.close();
                }
                if (this.cartConfirmationPopup) {
                    this.cartConfirmationPopup.close('Confirm');
                }
            };
        }
      },
      error: (err) => {
        this.searchService.errorCallBack(err);
      },
      complete: () => { },
    })
  };

    /**
     * Get esign document.
     * @param {type} args
     * @return void
    */
    getHSForm(args: {supplier_id: number, document_name: string}): void
    {

      var r = this.searchService.callDocument(args)
      .pipe(
        catchError(() => {
          return throwError(() => new Error('ups sommething happend'));
        })
      )
      .subscribe({
        next: (res: any) => {
          this.loadingPopup.close();
          if(res.data.url && res.data.client_id) {
            this.hellosign.url = res.data.url;
            this.hellosign.client_id = res.data.client_id;
            const client = new HelloSign({
              clientId: String(this.hellosign.client_id),
            });
            client.open(this.hellosign.url, {
              allowCancel: true,
              skipDomainVerification: true,
              debug: true,
            });
            client.on('sign', (data: any) => {
              client.close();
                if (this.reviewOrderPopup) {
                  this.reviewOrderPopup.close('Confirm');
                }
                if (this.firstOrderPopup) {
                  this.firstOrderPopup.close();
                }
                if (this.cartConfirmationPopup) {
                    this.cartConfirmationPopup.close('Confirm');
                }
            });
            client.on('close', () => {

            });
          }
        },
        error: (err) => {
          this.searchService.errorCallBack(err);
        },
        complete: () => { },
      })
    }

  /**
   * Close the written application modal
   * @return {undefined}
   */
  writtenClickOk() {
    if (this.writtenPopup) {
      this.writtenPopup.close();
    }
  };
}
