import { Barcode, ScanSettings } from 'scandit-sdk';
import { ScanditSdkBarcodePickerComponent, ScanditSdkService } from 'scandit-sdk-angular';

import { AfterViewInit, ChangeDetectorRef, Component, EventEmitter, Output, ViewChild, OnDestroy } from '@angular/core';

import { CameraErrorHandler } from './utils/camera-error.handler';
import { NativeContainerService } from './native-container.service';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

@Component({
  selector: 'lib-remission-shipping-document-scanner',
  templateUrl: 'remission-shipping-document-scanner-scandit.component.html',
  styleUrls: ['remission-shipping-document-scanner-scandit.component.scss'],
})
export class RemissionShippingDocumentScannerScanditComponent implements AfterViewInit, OnDestroy {
  public enabled = true;
  public errorAccess = false;
  public errorOther = false;
  public code = '';
  public ready = false;
  public webview = true;
  @Output() scan = new EventEmitter();
  @Output() manualEntry = new EventEmitter();
  destroy$ = new Subject();
  private activeSymbolCounts = [
    4,
    5,
    6,
    7,
    8,
    9,
    10,
    11,
    12,
    13,
    14,
    15,
    16,
    17,
    18,
    19,
    20,
    21,
    22,
    23,
    24,
    25,
    26,
    27,
    28,
    29,
    30,
    31,
    32,
  ];

  public settings: ScanSettings;

  @ViewChild('scanner') scanner: ScanditSdkBarcodePickerComponent;
  log = 'tst';
  constructor(private cameraError: CameraErrorHandler, private cdRef: ChangeDetectorRef, private native: NativeContainerService) {
    this.webview = this.native.isUiWebview();

    this.settings = new ScanSettings({
      enabledSymbologies: [Barcode.Symbology.CODE128, Barcode.Symbology.EAN13, Barcode.Symbology.INTERLEAVED_2_OF_5],
    });
    const twoOfFifeSymbology = this.settings.getSymbologySettings(Barcode.Symbology.INTERLEAVED_2_OF_5);
    twoOfFifeSymbology.setActiveSymbolCounts(this.activeSymbolCounts);
  }
  ngAfterViewInit() {
    this.webview = this.native.isUiWebview();

    if (this.webview) {
      this.cameraError.notAllowed.pipe(takeUntil(this.destroy$)).subscribe((v) => (this.errorAccess = v));

      try {
        this.scanner.error.pipe(takeUntil(this.destroy$)).subscribe(
          (success) => {
            this.scanErrorHandler(success);
            this.log = JSON.stringify(success);
          },
          (error) => {
            this.scanErrorHandler(error);
            this.log = JSON.stringify(error);
          }
        );
      } catch (error) {
        console.error(error);
      }
      this.ready = true;
    }
  }

  scanSuccess(result) {
    if (result.barcodes.length > 0) {
      this.code = result.barcodes[0].data;
      this.enabled = false;
      this.search();
    }
  }

  scanToggle() {
    this.enabled = true;
    this.ready = false;
    this.cdRef.detectChanges();
    setTimeout(() => this.cdRef.detectChanges(), 200);
  }

  public openNativeScanner() {
    this.destroy$.next();
    this.native
      .openScanner()
      .pipe(takeUntil(this.destroy$))
      .subscribe((data) => {
        this.code = JSON.stringify(data);

        if (data.status === 'SUCCESS') {
          this.code = data.data;
          this.scan.emit(this.code);
          this.enabled = false;
          this.cdRef.detectChanges();
        }
      });
  }

  search() {
    this.scan.emit(this.code);
  }

  isReady(scanner) {
    this.ready = true;
    const picker = (this.scanner['scanditSdkService'] as ScanditSdkService).picker as any;
    this.errorOther = !picker.scanner.isReadyToWork;
    picker.cameraManager.cameraSwitcherEnabled = false;
    picker.barcodePickerGui.cameraSwitcherElement = null;
    picker.cameraManager.triggerFatalError = (e) => {
      console.error(e);
      this.errorOther = true;
    };

    this.cdRef.detectChanges();
  }

  emitManualEntryIntent() {
    this.manualEntry.emit(true);
  }

  scanErrorHandler($event) {
    console.error($event);
    this.errorAccess = true;
  }

  ngOnDestroy() {
    this.destroy$.next();
  }
}
