import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy, ChangeDetectorRef, ViewRef } from '@angular/core';

@Component({
  selector: 'app-button',
  templateUrl: './button.component.html',
  styleUrls: ['./button.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ButtonComponent {
  @Input() id: string;
  @Input() primary = false;
  @Input() outline = false;
  @Input() round: boolean;
  @Input() type = 'medium';
  @Input() color: string;
  @Input() load = false;
  @Input() smallOffset = false;
  @Input() stayOnPage = false;
  @Input() disabled = false;
  @Input() primaryBorders = false;
  @Input() alignLeft = false;
  @Input() alignRight = false;
  @Input() alignBottom = false;
  @Output() action: EventEmitter<boolean> = new EventEmitter();
  @Output() loaded: EventEmitter<boolean> = new EventEmitter();
  loading = false;

  constructor(private cdrf: ChangeDetectorRef) {}

  onAction() {
    if (this.disabled) {
      return;
    }
    if (this.load && this.loading) {
      return;
    }
    this.action.emit(true);
  }

  startLoading() {
    if (!this.load) {
      console.error('In order to start loading, the load functionality has to be activated by passing [load]="true" to <app-button>');
      return;
    }
    this.loading = true;
    this.cdrf.detectChanges();
  }

  stopLoading() {
    setTimeout(() => {
      if (this.loading) {
        this.loaded.emit(true);
      }
      this.loading = false;
      if (this.stayOnPage) {
        try {
          this.detectChanges();
        } catch (error) {
          console.error(error);
        }
      }
    }, 400);
  }

  detectChanges() {
    setTimeout(() => {
      if (this.cdrf !== null && this.cdrf !== undefined && !(this.cdrf as ViewRef).destroyed) {
        this.cdrf.detectChanges();
      }
    }, 0);
  }
}
