import { Component, OnInit, Input } from '@angular/core';

import { ButtonState } from './button-state';

@Component({
  selector: 'button-save',
  template: require('./button-save.component.html'),
  styles:   [require('./button-save.component.scss')]
})
export class ButtonSaveComponent implements OnInit {
  // -------------------------------------------------------------------------
  // public properties
  // -------------------------------------------------------------------------

  withError: boolean             = false;
  type: string                   = 'primary';
  state: ButtonState             = ButtonState.NORMAL;
  buttonState                    = ButtonState;
  static timeoutMessages: number = 1000;

  // -------------------------------------------------------------------------
  // input/output
  // -------------------------------------------------------------------------

  @Input() id: string;
  @Input() disabled: boolean   = false;
  @Input() textSuccess: string = 'Saved...';
  @Input() textError: string   = 'Error...';

  private static instances = {};

  // -------------------------------------------------------------------------
  // constructor
  // -------------------------------------------------------------------------

  constructor() {
  }

  // -------------------------------------------------------------------------
  // methods
  // -------------------------------------------------------------------------

  ngOnInit() {
    if (!this.id) throw new Error('No id for compnent button save');
    ButtonSaveComponent.instances[this.id] = this;
  }

  static setState(id: string, state: ButtonState) {
    let d: ButtonSaveComponent = ButtonSaveComponent.instances[id];
    d.state                    = state;

    if (state === ButtonState.ERROR) {
      d.withError = true;
    }
    if (state === ButtonState.ERROR || state === ButtonState.FINISH) {
      setTimeout(() => {
        d.state = ButtonState.NORMAL;
      }, ButtonSaveComponent.timeoutMessages);
    }
  }


  onClick() {
    if (this.withError) this.withError = false;
  }
}
