// Angular Core
import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';

// Interfaces
import { ModalConfig, searchRenderInterface } from 'src/app/interfaces/common-interfaces';
import { SessionDataInterface } from 'src/app/interfaces/session-data-interface';

// Services
import { SearchService } from 'src/app/services/search/search.service';
import { SessionService } from 'src/app/services/session/session.service';
import { CartService } from 'src/app/services/cart/cart.service';
import { ReshopUnacceptedService } from 'src/app/services/reshopUnaccepted/reshop-unaccepted.service';
import { UtilitiesService } from 'src/app/services/utilities/utilities.service';

// RxJs
import { Subscription, catchError, throwError } from 'rxjs';
import { LoadingmodalComponent } from '../loadingmodal/loadingmodal.component';
import { HelloSignThankYouComponent } from '../hello-sign-thank-you/hello-sign-thank-you.component';
import { MinimumquantitynoticeComponent } from '../cart/place-order-popup/minimumquantitynotice/minimumquantitynotice.component';

// Modals
import { LessqtnmodalComponent } from './modals/lessqtnmodal/lessqtnmodal.component';
import { WrittenmodalComponent } from '../writtenmodal/writtenmodal.component';
import { FavoritesLimitReachedModalComponent } from './modals/favorites-limit-reached-modal/favorites-limit-reached-modal.component';
import { RefrigeratedComponent } from './modals/refrigerated/refrigerated.component';
import { NondcmodalComponent } from './modals/nondcmodal/nondcmodal.component';
import { AddedToCartMsgModalComponent } from './modals/added-to-cart-msg-modal/added-to-cart-msg-modal.component';

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

import { environment } from 'src/environments/environment';

type SearchRender = searchRenderInterface['other'][0][0];

interface ButtonStates extends SearchRender {
  buttonStates: {
    needsAccount: boolean,
    qtyInCart: number | null,
    inFavorites: number,
    addToCartAmount: number | null,
    controlStatus: boolean,
    favDisable: boolean,
    achRequired: boolean,
    renewApp : boolean,
    url: string,
    client_id: number,
  }
}

@Component({
  standalone: false,
  selector: 'app-add-to-cart',
  templateUrl: './add-to-cart.component.html',
  styleUrls: ['./add-to-cart.component.scss', './add-to-cart.component.query.scss']
})
export class AddToCartComponent implements OnInit {

  @Input() row!: searchRenderInterface['other'][0][0];
  @Input() fromPage!: string;

  session!: SessionDataInterface['data'];
  rowButtonStates: ButtonStates = {} as ButtonStates;
  queryParams: Params = {};
  url: string = location.pathname;
  customerSupportContact!: string;
  minPurchaseqty: number = 0;
  appliedSupplierId: number = 0;
  appliedAuctionId: number = 0;
  appliedMinQty: number = 0;
  appliedUnacceptedId: number = 0;
  args = {
    'supplier_id': 0,
    'document_name': ''
  };
  accountStatuses!: any;
  isPreviewMode!: boolean;
  imgPath: string = environment.imageUrl;
  constructor(
    private sessionService : SessionService,
    private searchService: SearchService,
    private modalService: NgbModal,
    private cartService: CartService,
    private reshopUnaccepted: ReshopUnacceptedService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private utilities: UtilitiesService
  ) { }

  ngOnInit(): void {
    this.session = this.sessionService.getSession();
    this.accountStatuses = this.utilities.getAccountStatuses();
    this.customerSupportContact = this.session.trxade_number;
    this.activatedRoute.queryParams.subscribe((params: Params) => {
        this.queryParams = params;
    });
    this.isPreviewMode = this.session.is_preview_mode;
    /**
     * Object to store button states
     * @type Object
     */
    this.rowButtonStates.buttonStates = {
      needsAccount: false,
      qtyInCart: 0,
      inFavorites: 0,
      addToCartAmount: 0,
      controlStatus: false,
      favDisable: false,
      achRequired: false,
      renewApp : false,
      url: '',
      client_id: 0
    };
    this.initCart();
  }

  /*
  * PRIVATE Method to initiate the add-to-cart directive state
  * keeping the state variables isolated from
  * what is incomming from the database and provide 
  * extra logic if necessary
  * @returns {undefined}
  */
  initCart() {
    //set button states based on data
    // needs account?
    this.row.unacceptedId = 0;
    this.row.btnFlag = false;
    if (this.row.unaccepted_auction) {
      this.row.unacceptedId = this.row.unaccepted_auction;
    }
    this.rowButtonStates.buttonStates.needsAccount = (this.row.account_no === '' || this.row.account_no === null);
    this.row.btnFlag = (this.row.status == "13" || this.row.status == "28" || this.row.status == "29");

    if(this.row.delay_new_account_results === 0) {
      this.rowButtonStates.buttonStates.needsAccount = false;
    }
    if(this.row.ach_required_for_brands === 1 && this.row.generic_or_brand === 'B' && this.row.ach_active === 0 && this.row.ach_authorization_form) {
      this.rowButtonStates.buttonStates.achRequired = true;
    }
    //qty in cart?
    this.rowButtonStates.buttonStates.qtyInCart = this.row.qty_in_cart;
    
    this.rowButtonStates.buttonStates.addToCartAmount = this.rowButtonStates.buttonStates.qtyInCart !== 0 ? this.rowButtonStates.buttonStates.qtyInCart : null;

    // in favorites?
    this.rowButtonStates.buttonStates.inFavorites = this.row.in_favorites;

    // set the controlStatus flag to apply for controls
    if(this.row.dea_schedule === 6 || this.row.dea_schedule === null) {
      this.rowButtonStates.buttonStates.controlStatus = false;
      this.rowButtonStates.buttonStates.renewApp = this.row.app_renewal_flag;
    } else {
      this.rowButtonStates.buttonStates.renewApp = false;
      if (this.row.require_cs_app === 0) {
          this.rowButtonStates.buttonStates.controlStatus = false;
      }
      else if(this.row.control_application_status === 15) {
          this.rowButtonStates.buttonStates.controlStatus = false;
      }
      else {
          this.rowButtonStates.buttonStates.controlStatus = true;
      }
    }
  };

  /*
  * PRIVATE methods hide and show spinner action is wrapped 
  * in a private methods incase we need 
  * to do some extra logic to properly 
  * hide and show sections with the spinner
  */
  showSpinner() {
    //code to show spinner here  
  };

  hideSpinner() {
      //code to hide spinner here
  };

  /**
   * Private property to set the status of refrigerated modal
   * @type boolean
   */
  RefrigeratedOpened: boolean = false;
                
  /*
   * Private property to set the base modal config
   * @type Object
   */
  refrigeratedConfig: ModalConfig = {
      showHeader: true,
      title: 'Refrigerated Product Notice'
  };

  /**
   * Private method to show the refrigerated modal
   * @returns null
   */
  refrigeratedModal!: NgbModalRef;
  showRefrigeratedModal() {
    this.refrigeratedModal = this.modalService.open(RefrigeratedComponent, {size: 'sm'});
    this.refrigeratedModal.componentInstance.refrigeratedModal = this.refrigeratedModal;
    this.refrigeratedModal.componentInstance.refrigeratedClickOk = this.refrigeratedClickOk;
    this.refrigeratedModal.componentInstance.refrigeratedClickCancel = this.refrigeratedClickCancel;
    this.refrigeratedModal.shown.subscribe(() => {
      this.RefrigeratedOpened = true;
    });

    this.refrigeratedModal.closed.subscribe(() => {
      this.RefrigeratedOpened = false;
    });
  };

  /**
   * Public method click ok in refrigerated modal
   */
  refrigeratedClickOk() {
    this.refrigeratedModal.close('ok');
  };

  /**
   * Public method click ok in refrigerated modal
   */
  refrigeratedClickCancel() {
    this.refrigeratedModal.close('cancel');
  };

  /**
   * Private property to set the status of lessquantity modal
   * @type boolean
   */
  LessQtyOpened: boolean = false;
  /**
   * Private property to store available amount
   * @type number
   */
  lessQtyRealAmount: number = 0;
  /**
   * Private property to store base-modal config
   * @type Object
   */
  lessQtyConfig: ModalConfig = {
    showHeader: true,
    title: 'Quantity Unavailable'
  };

  /**
   * Private method to show the refrigerated modal
   * @returns null
   */
  lessQtyModal!:NgbModalRef;
  showLessQtyModal() {
    this.lessQtyModal = this.modalService.open(LessqtnmodalComponent, {size: 'sm'})
    this.lessQtyModal.componentInstance.lessQtyRealAmount = this.lessQtyRealAmount;
    this.lessQtyModal.componentInstance.lessQtyModal = this.lessQtyModal;
    this.lessQtyModal.componentInstance.lessQtyClickOk = this.lessQtyClickOk;
    this.lessQtyModal.componentInstance.lessQtyClickCancel = this.lessQtyClickCancel;

    this.lessQtyModal.shown.subscribe(() => {
      this.LessQtyOpened = true;
    })

    this.lessQtyModal.closed.subscribe(() => {
      this.LessQtyOpened = false;
    })

    this.lessQtyModal.result.then(
      (data: string) => {
        this.LessQtyOpened = false;
        if(data === 'ok'){
          this.addToCart(this.row.auction_id, this.row.supplier_id, this.lessQtyRealAmount, this.minPurchaseqty, this.row.unacceptedId);
        }
        else if(data === 'cancel'){
          this.rowButtonStates.buttonStates.addToCartAmount = 0;
          this.rowButtonStates.buttonStates.qtyInCart = 0;
        }
      }
    );
  };

  /**
   * Public method click ok in refrigerated modal
   * @return {undefined}
   */
  lessQtyClickOk() {
    this.lessQtyModal.close('ok');
  };

  /**
   * Public method click ok in refrigerated modal
   * @return {undefined}
   */
  lessQtyClickCancel() {
    this.lessQtyModal.close('cancel');
  };

  /**
   * Private property to set the status of no Ndc modal
   * @type boolean
   */
  noNdcModalOpened: boolean = false;
                
  /**
   * Private property to store base-modal config
   * @type Object
   */
  noNdcConfig: ModalConfig = {
      showHeader: true,
      title: 'This Item Cannot Be Added to Favorites'
  };

  /**
   * Private method to show the noNDC modal
   * @returns null
   */
  noNdcModal!: NgbModalRef;
  showNoNdcModal() {
    this.noNdcModal = this.modalService.open(NondcmodalComponent, {size: 'sm'});
    this.noNdcModal.componentInstance.noNdcModal = this.noNdcModal;
    this.noNdcModal.componentInstance.noNdcClickOk = this.noNdcClickOk;
  };

  /**
   * Show modal when favorites limit is reached
   * @returns null
   */
  favoritesLimitReachedModal!: NgbModalRef;
  showFavoritesLimitReachedModal() {
    this.favoritesLimitReachedModal = this.modalService.open(FavoritesLimitReachedModalComponent, {size: 'sm'});
    this.favoritesLimitReachedModal.componentInstance.favoritesLimitReachedModal = this.favoritesLimitReachedModal;
    this.favoritesLimitReachedModal.componentInstance.closeFavLimitModal = this.closeFavLimitModal;
  };
  
  /**
   * Config for favorites limit reached modal
   * @type Object
   */
  favoritesLimitReachedConfig: ModalConfig = {
    showHeader: true,
    title: 'Cannot be added to Favorites '
  };

  /**
   * Close favorites limit reached modal.
   * @returns {undefined}
   */
  closeFavLimitModal() {
    this.favoritesLimitReachedModal.close();
  };

  /**
   * Public method click ok in noNdc modal
   * @return {undefined}
   */
  noNdcClickOk() {
    this.noNdcModal.close('Okay');
  };

  /**
   * Private property to set the status of addedToCartMsg modal
   * @type boolean
   */
  addedToCartMsgOpened: boolean = false;
  /**
   * Private property to store base-modal config
   * @type Object
   */
  addedToCartMsgConfig: ModalConfig = {
    showHeader: false,
    title: ''
  };

  /**
   * Private method to show the addedToCartMsg modal
   * @returns null
   */
  addedToCartMsgModal!:NgbModalRef;
  showAddedToCartMsgModal() {
    this.addedToCartMsgModal = this.modalService.open(AddedToCartMsgModalComponent, {size: 'sm'})
    this.addedToCartMsgModal.componentInstance.addedToCartMsgModal = this.addedToCartMsgModal;
    this.addedToCartMsgModal.componentInstance.closeAddedToCartMsgModal = this.closeAddedToCartMsgModal;
  };

  /**
   * Close AddedToCartMsgModal.
   * @return {undefined}
   */
  closeAddedToCartMsgModal() {
    this.addedToCartMsgModal.close();
  };

  /*
  * Public method to add to favorite or remove from favorite
  * @return {undefined}
  */
  addToFavSubscribe!: Subscription
  addToFav(itemNdc: string) {
    this.rowButtonStates.buttonStates.favDisable = true;
    if(this.rowButtonStates.buttonStates.inFavorites === 0) {
      var addToFavTemp = {};

      addToFavTemp = {
          ndc:itemNdc
      };

      this.addToFavSubscribe = this.searchService.addToFav(addToFavTemp)
        .pipe(
          catchError((err: HttpErrorResponse) => {
            if(err.status === 404 || err.status === 422) {
              this.rowButtonStates.buttonStates.favDisable = false;
              if (err.error.feedback[0] === 'Limit Reached') {
                  this.showFavoritesLimitReachedModal();
              } else {
                  this.showNoNdcModal();
              }
            }
            return throwError(() => new Error('ups sommething happend'));
          })
        )
        .subscribe({
          next: () => {
            this.rowButtonStates.buttonStates.inFavorites  = 1;
            this.rowButtonStates.buttonStates.favDisable = false;
          },
          error: (err: HttpErrorResponse) => {
            if(err.status === 404 || err.status === 422) {
              this.rowButtonStates.buttonStates.favDisable = false;
              if (err.error.feedback[0] === 'Limit Reached') {
                  this.showFavoritesLimitReachedModal();
              } else {
                  this.showNoNdcModal();
              }
            }
            this.searchService.errorCallBack(err);
          },
          complete: () => { },
        })
    }
    else if(this.rowButtonStates.buttonStates.inFavorites === 1) {
      var removeFromFavTemp = {};
      
      removeFromFavTemp = {
          ndc:itemNdc,
          action: 'remove'
      };

      this.addToFavSubscribe = this.searchService.addToFav(removeFromFavTemp)
        .pipe(
          catchError((err: HttpErrorResponse) => {
            if(err.status === 422 || err.status === 404) {
              this.showNoNdcModal();
              this.rowButtonStates.buttonStates.favDisable = false;
            }
            return throwError(() => new Error('ups sommething happend'));
          })
        )
        .subscribe({
          next: () => {
            this.rowButtonStates.buttonStates.inFavorites  = 0;
            this.rowButtonStates.buttonStates.favDisable = false;
          },
          error: (err: HttpErrorResponse) => {
            if(err.status === 422 || err.status === 404) {
              this.showNoNdcModal();
              this.rowButtonStates.buttonStates.favDisable = false;
            }
            this.searchService.errorCallBack(err);
          },
          complete: () => { },
        })
    }
  };

  /*
  * PUBLIC method to add to cart action
  * @return {undefined}
  */
  removeFromCartSubscribe!: Subscription;
  addToCartSubscribe!: Subscription;
  addToCart(auction_id: number, supplier_id: number, qty: any, minPurchaseQuantity: number, unacceptedId: number) {
    //qty must be greater than or equal to 1
    if (qty < 0) {
        this.addButtonFlag = false;
        return null;
    }
    //remove from cart if qty is 0
    if(Number.parseInt(qty) === 0) {
      this.addButtonFlag = false;
      var list = [];
      
      list.push(auction_id);

      this.removeFromCartSubscribe = this.cartService.removeFromCart(list)
        .pipe(
          catchError(() => {
            return throwError(() => new Error('ups sommething happend'));
          })
        )
        .subscribe({
          next: () => {
            //trigger event to refresh cart count
            //trigger event to refresh quickcart
            this.cartService.QuickCart.emit("");
            //Refresh shipping options
            this.cartService.updateShippingInfo.emit({});
            this.rowButtonStates.buttonStates.qtyInCart = 0;
            this.rowButtonStates.buttonStates.addToCartAmount = null;
          },
          error: (err) => {
            this.cartService.errorCallBack(err);
          },
          complete: () => { },
        })
        return false;
    }
    if(this.checkPurchaseQuantity(qty, minPurchaseQuantity) === null){
        this.addButtonFlag = false;
        return null;
    }

    // //check if product is refrigerated
    if(this.row.is_refrigerated) {
        //check if the modal is open already
        if(!this.RefrigeratedOpened) {
          //create and dispay modal
          this.showRefrigeratedModal();
          //we stop the add to cart and wait for user response from modal
          this.refrigeratedModal.result.then(
            (data: string) => {
              this.RefrigeratedOpened = false;
              if(data === 'ok'){
                this.addToCartData(auction_id, supplier_id, qty, minPurchaseQuantity, unacceptedId);
              }
              return null;
            }
          );
        }
    } else {
      this.addToCartData(auction_id, supplier_id, qty, minPurchaseQuantity, unacceptedId);
    }
    return null;
  };

  addToCartData(auction_id: number, supplier_id: number, qty: number, minPurchaseQuantity: number, unacceptedId: number){
    let sourceName = "";
    let fromPage = this.getFromPage();
    if (this.queryParams['sourceName'] !== undefined) {
        sourceName = this.queryParams['sourceName'];
        fromPage = (this.queryParams['sourceFrom'] === undefined) ? "Banner Ad" : this.queryParams['sourceFrom'];
    }
    this.addToCartSubscribe = this.cartService.addToCart(auction_id, supplier_id, qty, fromPage, sourceName)
    .pipe(
      catchError((err: HttpErrorResponse) => {
        this.addToCartResponseError(err, minPurchaseQuantity);
        return throwError(() => new Error('ups sommething happend'));
      })
    )
    .subscribe({
      next: () => {
        this.showSpinner();
        //Success
        //update our qty in cart
        //need to get the amount from the response object
        this.rowButtonStates.buttonStates.qtyInCart  = this.rowButtonStates.buttonStates.addToCartAmount;
        //trigger event to refresh cart count
        this.cartService.RefreshQuickCart.emit('');
        //trigger event to refresh quickcart
        this.cartService.QuickCart.emit("");
        //Refresh shipping options
        this.cartService.updateShippingInfo.emit({});
        //hide spinner
        this.hideSpinner();
        if (unacceptedId > 0) {
          this.reshopUnaccepted.saveReshopAuctions(unacceptedId, auction_id).subscribe({
            error: (err: HttpErrorResponse) =>
                this.reshopUnaccepted.errorCallBack(err)
            });
        }
      },
      error: (err: HttpErrorResponse) => {
        this.addToCartResponseError(err, minPurchaseQuantity);
        return this.cartService.errorCallBack(err);
      },
      complete: () => { },
    })
  }

  addToCartResponseError(error: HttpErrorResponse, minPurchaseQuantity: number){
    if (error.status === 400) { //generic error
      alert(error.error.feedback[0].replace(/"/g, ''));
    }
    if (error.status === 422) { //not enought qty
      this.lessQtyRealAmount = error.error.validation.qty_available;//need to replacethis with response data
      this.rowButtonStates.buttonStates.addToCartAmount = this.lessQtyRealAmount;
      this.minPurchaseqty = minPurchaseQuantity;
      this.showLessQtyModal();
      return null;
    }
    // hide spinner
    this.hideSpinner();
    setTimeout(() => {
      this.addButtonFlag = false;
    }, 1500);
    return null;
  }

  /**
   * Returns the Page where a Product is added to Cart, if it was configured in Directive.
   * @returns {string}
   */
  getFromPage() {
    var fromPage = '';
    if (this.fromPage !== undefined && this.fromPage !== null && this.fromPage !== '') {
      fromPage = this.fromPage;
    }
    return fromPage;
  };

  /**
  * Config for written modal
  */
  writtenConfig = {
    showHeader: true,
    title: 'CHECK YOUR EMAIL',
    class: 'signatureTypeWritten' 
  };

  /*
  * Method to update status
  */
  updateEsignSubscribe!: Subscription;
  updateButtonStatus(args: any) {
    var params = {
        'supplier_id': args.supplier_id,
        'action': "process",
        'type': "ControlDocument"
    };
    if (this.flag) {
      params.type = "CreditDocument";
    }
    
    this.updateEsignSubscribe = this.searchService.updateEsign(params)
      .pipe(
        catchError(() => {
          return throwError(() => new Error('ups sommething happend'));
        })
      )
      .subscribe({
        next: () => {
          this.searchService.searchBySearchQuery.emit({resetFilters: true});
          this.searchService.supplierSearchBySearchQuery.emit({resetFilters: true});
          this.searchService.oppBuysSearchBySearchQuery.emit({});
          this.searchService.shortDatedSearchBySearchQuery.emit({});
          this.searchService.controlsPageQuery.emit({});
        },
        error: (err: HttpErrorResponse) => {
          this.cartService.errorCallBack(err);
        },
        complete: () => { }
      });
  };

  /**
   * Close the written application modal
   * @return {undefined}
   */
  writtenClickOk() {
    this.writtenModal.close('ok');
  };
  /**
   * Config for loading modal
   */
  loadingConfig: ModalConfig = {
      showHeader: true,
      title: 'Loading'
  };

  /**
   * get the response for control or supplier document (esign or written)
   * @param {type} args
   * @return {undefined}
   */
  callDocumentSubscribe!: Subscription;
  writtenModal!: NgbModalRef;
  getForm(args: any) {
    this.callDocumentSubscribe = 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.rowButtonStates.buttonStates.url = res.data.url;
            this.rowButtonStates.buttonStates.client_id = res.data.client_id;

            const client = new HelloSign({
              clientId: String(this.rowButtonStates.buttonStates.client_id),
            });

            client.open(this.rowButtonStates.buttonStates.url, {
              allowCancel: true,
              skipDomainVerification: true,
              debug: true,
            });

            client.on('sign', (data: any) => {
                if (this.appliedAuctionId !== 0) {
                    this.addToCart(
                        this.appliedAuctionId,
                        this.appliedSupplierId,
                        this.appliedMinQty,
                        this.appliedMinQty,
                        this.appliedUnacceptedId
                    );
                }
                this.helloSignThankYou();
                this.updateButtonStatus(args);
              client.close();
            });

            client.on('close', () => {
            });

          } else if(res.data.supplierName && res.data.buyerEmail) {
            var row :{supplierName: string, buyerEmail: string} = {
              supplierName : res.data.supplierName,
              buyerEmail : res.data.buyerEmail
            };
            //written
            this.writtenModal = this.modalService.open(WrittenmodalComponent, {size: 'sm'})
            this.writtenModal.componentInstance.row = row;
            this.writtenModal.componentInstance.title = "INFORMATION";
            this.writtenModal.componentInstance.writtenModal = this.writtenModal;
            this.writtenModal.componentInstance.writtenClickOk = this.writtenClickOk;

            this.writtenModal.shown.subscribe(() => {
                this.updateButtonStatus(args);
                if (this.appliedAuctionId !== 0) {
                    this.addToCart(
                       this.appliedAuctionId,
                       this.appliedSupplierId,
                       this.appliedMinQty,
                       this.appliedMinQty,
                       this.appliedUnacceptedId
                   );
                }
            });
            this.writtenModal.closed.subscribe(() => {
                if (this.appliedAuctionId !== 0) {
                    this.showAddedToCartMsgModal();
                }
            })
          }
        },
        error: (err: HttpErrorResponse) => {
          this.cartService.errorCallBack(err);
        },
        complete: () => { }
      });
  };

  flag: boolean = false; 
  /*
  * Public method when user clicks on apply now button
  * @return {null}
  */
  loadingPopup!: NgbModalRef
  applyNow(row: searchRenderInterface['other'][0][0]) {
      //ask if he has an existing account number with supplier?
      
      //if yes then save account number and refresh results
      
      //if no then continue with application:
      this.appliedSupplierId = row.supplier_id;
      this.appliedAuctionId  = row.auction_id;
      this.appliedMinQty = row.min_purchase_quantity;
      this.appliedUnacceptedId = row.unacceptedId;
      this.args = {
          'supplier_id': row.supplier_id,
          'document_name': 'SupplierDocument'
      };
      //loading modal
      this.loadingPopup = this.modalService.open(LoadingmodalComponent, {size: 'sm'});
      this.flag = true;
      this.getForm(this.args);
      return null;
  };

  /**
   * Method when user clicks apply for controls button
   * @return {undefined}
   */
  applyForControls(row: searchRenderInterface['other'][0][0]) {
    this.appliedSupplierId = row.supplier_id;
    this.args = {
        'supplier_id': row.supplier_id,
        'document_name': 'ControlsDocument'
    };
    
    //loading modal
    this.loadingPopup = this.modalService.open(LoadingmodalComponent, {size: 'sm'});
    this.getForm(this.args);
    return null;
  };

  /**
   * Redirect to manage suppliers page
   * @return {undefined}
   */
  checkStatus(supplierName: string) {
    this.router.navigate(['/market/manageSupplier'], { queryParams: { supp: supplierName.replace(/[^a-zA-Z0-9]/g, '').toLowerCase() } })
  };

  /**
   * Call addToCart function when enter key pressed
   * @param {type} $event
   * @param {type} id
   * @param {type} supplier_id
   * @param {type} amt
   * @return {undefined}
   */
  addOnEnter(event: any, id: number, supplier_id: number, amt: number, minPurchaseQuantity: number, unacceptedId: number) {
    if(!this.addOnEnterFlag) {
      if(event.keyCode === 13 && amt > 0) {
        this.addToCart(id, supplier_id, amt, minPurchaseQuantity, unacceptedId);
        this.addOnEnterFlag = true;
      }
      setTimeout(() => {
        this.addOnEnterFlag = false;
      }, 2500);
    }
  };

  /**
   * checkInput
   */
  checkInput(){
    var intPas = this.rowButtonStates.buttonStates.addToCartAmount;
    
    if ((intPas ?? 0) < 0 || isNaN(intPas ?? 0)) {
        this.rowButtonStates.buttonStates.addToCartAmount = 0;
    } else {
        this.rowButtonStates.buttonStates.addToCartAmount = intPas;
    }
  };

  checkDescription(packageDescription: string, customNote: string) {
    if ((packageDescription !== null && packageDescription !== '' && packageDescription.trim().split(',')[0] !== 'bottle') || 
       (customNote !== null && customNote !== '')) {
        return true;
    } else {
        return false;
    }
  };

  toolTip = {
    title: "<b class='toolTipTitle'>PACKAGE DESCRIPTION: </b>"
  };

  /**
   * Hello sign thank you Modal
   * @returns {undefined}
   */
  helloSignThankYouModal!:NgbModalRef;
  helloSignThankYou() {
    this.helloSignThankYouModal = this.modalService.open(HelloSignThankYouComponent, {size: 'sm'})
    this.helloSignThankYouModal.componentInstance.helloSignThankYouClickOk = this.helloSignThankYouClickOk.bind(this);
    this.helloSignThankYouModal.componentInstance.customerSupportContact = this.customerSupportContact;
    this.helloSignThankYouModal.componentInstance.helloSignThankYouModal = this.helloSignThankYouModal;
    this.helloSignThankYouModal.componentInstance.redirectSuppliers = this.redirectSuppliers;
    this.helloSignThankYouModal.componentInstance.helloSignThankYouClickOk = () => {
        if (this.appliedAuctionId !== 0) {
            this.showAddedToCartMsgModal();
        }
        this.args = {
            'supplier_id': this.appliedSupplierId,
            'document_name': 'SupplierDocument'
        };
        this.updateButtonStatus(this.args);
            this.helloSignThankYouClickOk()
    };
  };

  /**
   * Private property to store base-modal config
   * @type Object
   */
  helloSignThankYouConfig = {
    showHeader: false
  };

  /**
   * Public method click ok
   * @return {undefined}
   */
  helloSignThankYouClickOk() {
    this.helloSignThankYouModal.close('Ok');
  };

  /**
  * redirect to manage suppliers page
  * @return {undefined}
  */
  redirectSuppliers () {
    this.args = {
        'supplier_id': this.appliedSupplierId,
        'document_name': 'SupplierDocument'
    };
    this.updateButtonStatus(this.args);
    this.checkStatus(String(this.appliedSupplierId));
  };

  addButtonFlag: boolean = false;
  addOnEnterFlag: boolean = false;

  /**
  * Private property to set the status of MinimumQuantityNotice modal
  * @type boolean
  */
  MinimumQuantityNoticeOpened: boolean = false;

  /**
   * Private property to store base-modal config
   * @type Object
   */
  minimumQuantityNoticeConfig: ModalConfig = {
    showHeader: true,
    title: 'Minimum Purchase Quantity Alert'
  };

  /**
   * Private method to show the MinimumQuantityNotice modal
   * @returns null
   */
  showMinimumQuantityPopup!: NgbModalRef
  showMinimumQuantityNoticeModal(errorMsg: string) {
    this.showMinimumQuantityPopup = this.modalService.open(MinimumquantitynoticeComponent, {size: 'sm'});
    this.showMinimumQuantityPopup.componentInstance.errorMsg = errorMsg
    this.showMinimumQuantityPopup.componentInstance.showMinimumQuantityPopup = this.showMinimumQuantityPopup
    this.showMinimumQuantityPopup.componentInstance.clickOk = this.clickOk
  };

  /**
   * Public method click ok in refrigerated modal
   * @return {undefined}
   */
  clickOk() {
    this.showMinimumQuantityPopup.close('ok');
  };

  /**
   * 
   * @param {int} quantity
   * @param {int} minPurchaseQuantity
   * @returns {Boolean}
   */
  checkPurchaseQuantity(quantity: number, minPurchaseQuantity: number) {
    if (quantity < minPurchaseQuantity) {
        var neededQuantity = minPurchaseQuantity - quantity;
        var errorMsg = "There is a minimum quantity of "+minPurchaseQuantity+" to purchase this product. Please add "+neededQuantity+" more to your cart to continue to purchase.";
        this.showMinimumQuantityNoticeModal(errorMsg);
        return null;
    }
    return true;
  };
}
