import { Component, OnInit, ViewChild, ElementRef, AfterViewInit, ViewEncapsulation } from '@angular/core';
import { isNullOrUndefined } from 'util';
import { Store } from '@ngxs/store';
import { RemissionService, RemissionProduct } from '@isa/remission';
import { take } from 'rxjs/operators';
import { SetRemissionSearchedProduct } from 'apps/sales/src/app/core/store/actions/remission.actions';
import { ResetBreadcrumbsTo } from 'apps/sales/src/app/core/store/actions/breadcrumb.actions';
import { SetBranchProcessCurrentPath } from 'apps/sales/src/app/core/store/actions/branch-process.actions';
import { Router } from '@angular/router';
import { isEmptyString } from 'apps/sales/src/app/core/utils/app.utils';
import { SearchInputComponent } from '@libs/ui';
import { RemissionScanProductInvalidBarcodeComponent } from '../../components/remission-scan-product-invalid-barcode/remission-scan-product-invalid-barcode.component';

@Component({
  selector: 'app-remission-add-product-to-remission-list',
  templateUrl: './remission-add-product-to-remission-list.component.html',
  styleUrls: ['./remission-add-product-to-remission-list.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class RemissionAddProductToRemissionListComponent implements OnInit, AfterViewInit {
  errorMessage: string;

  @ViewChild('input') input: ElementRef;
  @ViewChild('searchInput') searchInput: SearchInputComponent;
  @ViewChild('invalidBarcodeDialog')
  invalidBarcodeDialog: RemissionScanProductInvalidBarcodeComponent;

  constructor(private store: Store, private remissionService: RemissionService, private router: Router) {}

  ngOnInit() {}

  ngAfterViewInit() {
    this.searchInput.focus();
  }

  searchProduct(input: string) {
    this.validInput(input).ifTrue(() => {
      this.remissionService
        .searchProduct({ ean: input })
        .pipe(take(1))
        .subscribe(this.searchProductResultHandler, (error) => {
          console.error(error);
          this.store.dispatch(new SetRemissionSearchedProduct(undefined));
          this.setNoResultsError();
          this.invalidBarcodeDialog.openDialog();
        });
    });
  }

  searchProductResultHandler = (remissionProduct: RemissionProduct) => {
    if (isNullOrUndefined(remissionProduct)) {
      this.store.dispatch(new SetRemissionSearchedProduct(undefined));
      this.setNoResultsError();
      this.invalidBarcodeDialog.openDialog();
      return;
    }
    this.store.dispatch(new SetRemissionSearchedProduct(remissionProduct));
    this.navigateRemissionCreateList();
  };

  validInput(input: string) {
    if (isEmptyString(input)) {
      this.setRequiredError();
      return false;
    }

    if (!new RegExp(/^\d+$/).test(input)) {
      this.setInvalidFormatError();
      return false;
    }

    this.clearErrors();
    return true;
  }

  navigateRemissionCreateList() {
    const path = '/remission/create';
    const queryParams = { mode: 'addProduct' };

    this.store.dispatch(
      new ResetBreadcrumbsTo(
        {
          path: path,
          name: 'Remission',
          queryParams: queryParams,
        },
        'remission'
      )
    );
    this.router.navigate([path], { queryParams: queryParams });
    this.store.dispatch(new SetBranchProcessCurrentPath(path, true, queryParams));
  }

  clearErrors() {
    this.errorMessage = null;
  }

  setRequiredError() {
    this.errorMessage = 'ISBN/EAN wird benötigt';
  }

  setInvalidFormatError() {
    this.errorMessage = 'ISBN/EAN code Format ist nicht korrekt';
  }

  setNoResultsError() {
    this.errorMessage = 'Ergibt keine Suchergebnisse';
  }
}
