import { Component, Input, Output, EventEmitter, OnChanges, SimpleChanges, OnInit } from '@angular/core';
import { IFeedback } from './feedback.interface';
import { FeedbackType } from './feedback-type.enum';

/**
 * Feedback Component
 * @export
 * @class FeedbackComponent
 * @implements {OnInit}
 */
@Component({
  selector: 'sts-feedback',
  templateUrl: './feedback.component.html',
  styleUrls: ['./feedback.component.scss']
})
export class FeedbackComponent implements OnChanges, OnInit {

  @Input() public model: IFeedback;
  @Input()
  set shouldCloseAfterTimeout(value: string) {
    this._shouldCloseAfterTimeout = value === 'true' ? true : false;
  }

  @Input() public timeoutValue: number;

  @Output() public close: EventEmitter<void> = new EventEmitter<void>();

  private _shouldCloseAfterTimeout: boolean;
  private _defaultTimeout = 5000;

  constructor() {}

  public ngOnInit(): void {
    this.timeoutValue = this.timeoutValue ? this.timeoutValue : this._defaultTimeout;
  }

  public ngOnChanges(changes: SimpleChanges): void {
    if (changes.model && changes.model.currentValue) {
      this.model.displayClose = this.model.displayClose === undefined ? true : this.model.displayClose;
      if (this.model.displayClose) {
        setTimeout(() => {
          this.clearMessage();
        }, this.timeoutValue);
      }
    }
  }

  /**
   * This method is responsible for setting message class.
   *
   * @readonly
   * @type {object}
   * @memberof FeedbackComponent
   */
  public get messageClass(): object {
    return {
      'gen-msg__error': this.model.type === FeedbackType.Error,
      'gen-msg__warning': this.model.type === FeedbackType.Warning,
      'gen-msg__notification': this.model.type === FeedbackType.Notification,
      'gen-msg__success': this.model.type === FeedbackType.Success
    };
  }

  /**
   * This method is responsible for clearing message thus removing view
   *
   * @memberof FeedbackComponent
   */
  public clearMessage(): void {
    this.model = null;
    this.close.emit();
  }
}
