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-product-scanner',
  templateUrl: 'remission-product-scanner-scandit.component.html',
  styleUrls: ['remission-product-scanner-scandit.component.scss'],
})
export class RemissionProductScannerScanditComponent 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();

  public settings = new ScanSettings({
    enabledSymbologies: [Barcode.Symbology.CODE128, Barcode.Symbology.EAN13],
  });

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

  ngAfterViewInit() {
    this.webview = this.native.isUiWebview();

    if (this.webview) {
      this.cameraError.notAllowed.subscribe((v) => (this.errorAccess = v));

      try {
        this.scanner.error.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.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();
  }
}
