import { Component, ChangeDetectionStrategy, Input, ChangeDetectorRef, OnDestroy } from '@angular/core';
import { merge, Subscription } from 'rxjs';
import { IInput, FilterInput } from '../../tree';

@Component({
  selector: 'shared-filter-input-chip',
  templateUrl: 'filter-input-chip.component.html',
  styleUrls: ['filter-input-chip.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: false,
})
export class FilterInputChipComponent implements OnDestroy {
  private _input: FilterInput;

  @Input()
  set input(value: IInput) {
    if (value instanceof FilterInput) {
      this._input = value;
    } else {
      this._input = FilterInput.create(value);
    }
    this.registerChanges();
  }

  get uiInput() {
    return this._input;
  }

  private changeSubscription: Subscription;

  constructor(private cdr: ChangeDetectorRef) {}

  ngOnDestroy() {
    this.unregisterChanges();
  }

  registerChanges() {
    this.unregisterChanges();

    if (this.uiInput) {
      merge(this.uiInput.changes, ...(this.uiInput?.options?.values?.map((o) => o.changes) || [])).subscribe(() => {
        this.cdr.markForCheck();
      });
    }
  }

  unregisterChanges() {
    this.changeSubscription?.unsubscribe();
    this.changeSubscription = new Subscription();
  }
}
