import { AfterContentInit, Directive, HostBinding, OnDestroy } from '@angular/core';
import { MatStepper } from '@angular/material/stepper';
import { merge, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

/**
 * Directive attached to the Angular Material horizontal stepper to provide activation-states for each step in order
 * to style connection lines between the steps 50:50 as defined in the Brandguide.
 */
@Directive({
  // eslint-disable-next-line @angular-eslint/directive-selector
  selector: 'mat-horizontal-stepper',
})
export class HorizontalStepperDirective implements AfterContentInit, OnDestroy {
  @HostBinding('class.stepper--step00-active') step0Active = false;
  @HostBinding('class.stepper--step01-active') step1Active = false;
  @HostBinding('class.stepper--step02-active') step2Active = false;
  @HostBinding('class.stepper--step03-active') step3Active = false;
  @HostBinding('class.stepper--step04-active') step4Active = false;
  @HostBinding('class.stepper--step05-active') step5Active = false;
  @HostBinding('class.stepper--step06-active') step6Active = false;
  @HostBinding('class.stepper--step07-active') step7Active = false;
  @HostBinding('class.stepper--step08-active') step8Active = false;
  @HostBinding('class.stepper--step09-active') step9Active = false;

  protected onDestroy$ = new Subject<void>();

  constructor(private host: MatStepper) {}

  ngAfterContentInit(): void {
    merge(this.host.selectionChange.asObservable(), this.host.animationDone.asObservable(), this.host.steps.changes)
      .pipe(takeUntil(this.onDestroy$))
      .subscribe((data) => {
        const cdkSteps = this.host.steps.toArray();
        for (let i = 0; i < cdkSteps.length && i < 10; i++) {
          if(cdkSteps[i].interacted && data && data.previouslySelectedIndex < data.selectedIndex && data.previouslySelectedIndex==i)
            this['step' + i + 'Active'] = i < cdkSteps.length ? cdkSteps[i].completed : false;
          else if(!cdkSteps[i].interacted)
          this['step' + i + 'Active'] = false;
        }
      });
  }

  ngOnDestroy() {
    this.onDestroy$.next();
    this.onDestroy$.complete();
  }
}
