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

@Component({
  selector: 'ui-input-option-tri-state',
  templateUrl: 'filter-input-option-tri-state.component.html',
  styleUrls: ['filter-input-option-tri-state.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UiInputOptionTriStateComponent implements OnDestroy {
  private _option: UiOption;

  @Input()
  set option(value: IUiOption) {
    if (value instanceof UiOption) {
      this._option = value;
    } else {
      this._option = UiOption.create(value);
    }
    this.subscribeChanges();
  }

  get uiOption() {
    return this._option;
  }

  optionChangeSubscription = new Subscription();

  constructor(private cdr: ChangeDetectorRef) {}

  ngOnDestroy() {
    this.unsubscribeChanges();
  }

  subscribeChanges() {
    this.unsubscribeChanges();
    if (this.uiOption) {
      this.optionChangeSubscription.add(
        this.uiOption.changes.subscribe(() => {
          this.cdr.markForCheck();
        })
      );
    }
  }

  unsubscribeChanges() {
    this.optionChangeSubscription.unsubscribe();
    this.optionChangeSubscription = new Subscription();
  }
}
