import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Inject, OnDestroy, OnInit } from '@angular/core';
import { toastAnimations, ToastAnimationState, slideAnimationTime } from './animation';
import { Toast, ToastRef } from './defs';
import { TOAST_CONFIG_TOKEN } from './tokens';

@Component({
  selector: 'lib-toast',
  templateUrl: 'toast.component.html',
  styleUrls: ['toast.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  animations: [toastAnimations.slideToast],
})
export class ToastComponent implements OnInit, OnDestroy {
  timeoutRef: NodeJS.Timeout;
  animationState: ToastAnimationState = 'default';
  width: string = '55.25rem';

  constructor(
    @Inject(TOAST_CONFIG_TOKEN) public readonly data: Toast,
    private readonly _ref: ToastRef,
    private readonly _cdr: ChangeDetectorRef
  ) {}

  ngOnInit(): void {
    if (this.data?.size) {
      this.width = this.data?.size === 'width-full' ? '100vw' : '55.25rem';
    }

    this.timeoutRef = setTimeout(() => {
      this.close();
      this._cdr.markForCheck();
    }, slideAnimationTime + (this.data.timer ?? 5000));
  }

  ngOnDestroy() {
    clearTimeout(this.timeoutRef);
  }

  close() {
    this.animationState = 'closing';
  }

  onSlideFinished(event: AnimationEvent) {
    if (this.animationState === 'closing') {
      this._ref.close();
    }
  }
}
