import { Component, ChangeDetectionStrategy, Host, OnInit, OnDestroy, ChangeDetectorRef, forwardRef, EventEmitter } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { BehaviorSubject, Subscription } from 'rxjs';
import { first, map } from 'rxjs/operators';

@Component({
  selector: 'shared-goods-in-out-order-details-tags',
  templateUrl: 'goods-in-out-order-details-tags.component.html',
  styleUrls: ['goods-in-out-order-details-tags.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => SharedGoodsInOutOrderDetailsTagsComponent), multi: true }],
})
export class SharedGoodsInOutOrderDetailsTagsComponent implements OnInit, OnDestroy, ControlValueAccessor {
  selected$ = new BehaviorSubject<string>('');

  readonly defaultTags = ['Maxi', 'Mini', 'Kleinkram', 'Nonbook', 'Kalender'];

  inputValueSubject = new BehaviorSubject<string>('');

  inputValue$ = this.inputValueSubject.asObservable();

  disabled = false;

  private onChange = (value: string) => {};

  private onTouched = () => {};

  get inputValue() {
    return this.inputValueSubject.value;
  }

  controlSize$ = this.inputValue$.pipe(map((value) => (value ? Math.min(value?.length, 15) : 3)));

  private subscription = new Subscription();

  constructor(private _cdr: ChangeDetectorRef) {}

  writeValue(obj: any): void {
    this.selected$.next(obj);
    this._cdr.markForCheck();
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  setDisabledState?(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }

  ngOnInit() {
    this.subscription.add(
      this.selected$.pipe(map((selected) => (this.defaultTags.includes(selected) ? '' : selected))).subscribe(this.inputValueSubject)
    );
  }

  ngOnDestroy() {
    this.inputValueSubject.unsubscribe();
    this.subscription.unsubscribe();
  }

  async setCompartmentInfo(compartmentInfo: string) {
    const currentCompartmentInfo = await this.selected$.pipe(first()).toPromise();
    if (currentCompartmentInfo === compartmentInfo) {
      this.onChange(undefined);
      this.selected$.next(undefined);
    } else {
      this.onChange(compartmentInfo);
      this.selected$.next(compartmentInfo);
    }

    this._cdr.markForCheck();
  }
}
