import { Component, OnInit, AfterViewInit, OnDestroy, Output, EventEmitter } from '@angular/core';
import { ModalService } from '@libs/ui';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { isNullOrUndefined } from 'util';

@Component({
  selector: 'app-customer-card-manual-entry',
  templateUrl: './customer-card-manual-entry.component.html',
  styleUrls: ['./customer-card-manual-entry.component.scss'],
})
export class CustomerCardManualEntryComponent implements OnInit, AfterViewInit, OnDestroy {
  id = 'customer-card-manual-entry-modal';
  constructor(private modalService: ModalService) {}
  focusManager$ = new Subject<number>();
  destroy$ = new Subject();
  @Output() scanner = new EventEmitter();
  @Output() scan = new EventEmitter<string>();

  code = ['', '', '', '', '', '', '', ''];

  get disabled() {
    let status = false;
    this.code.forEach((entry) => {
      if (isNullOrUndefined(entry) || entry === '' || entry === ' ') {
        status = true;
      }
    });
    return status;
  }

  ngOnInit() {}

  ngAfterViewInit() {
    this.focusManager$.pipe(takeUntil(this.destroy$)).subscribe((codeIndex) => {
      document.getElementById('code-' + codeIndex).focus();
    });
  }

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

  openDialog() {
    this.modalService.open(this.id);
    this.focusManager$.next(0);
  }

  closeDialog() {
    this.modalService.close(this.id);
  }

  valueChanged(index: number) {
    if (isNullOrUndefined(this.code[index]) || this.code[index] === '' || this.code[index] === ' ') {
      return;
    }
    if (index !== 7) {
      this.focusManager$.next(index + 1);
    }
  }

  onKey(index: number, event: any) {
    if (event.keyCode === 8 && index !== 0) {
      this.focusManager$.next(index - 1);
    }
  }

  openScanner() {
    this.scanner.emit(true);
  }

  onScan() {
    const fullCode = this.code.reduce((c1, c2) => c1 + c2).toUpperCase();
    this.scan.emit(fullCode);
  }
}
