import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { DoubleChoiceSwitch } from './model/double-choice-switch.model';
import { state, trigger, transition, animate, style } from '@angular/animations';

@Component({
  selector: 'lib-double-choice-switch',
  templateUrl: './double-choice-switch.component.html',
  styleUrls: ['./double-choice-switch.component.scss'],
  animations: [
    trigger('buttonState', [
      state(
        'inactive',
        style({
          width: '160px',
          left: 0,
        })
      ),
      state(
        'active',
        style({
          width: '71px',
          left: '198px',
        })
      ),
      transition('inactive => active', animate('150ms')),
      transition('active => inactive', animate('150ms')),
    ]),
  ],
})
export class DoubleChoiceSwitchComponent implements OnInit {
  @Input()
  get model(): DoubleChoiceSwitch {
    return this._model;
  }
  set model(value: DoubleChoiceSwitch) {
    this._model = value;
    if (value) {
      this.state = this.model.isFirstSwitchedOn ? 'inactive' : 'active';
    }
  }
  @Input() animations = false;
  @Output() change = new EventEmitter<DoubleChoiceSwitch>();
  state = 'inactive';
  private _model: DoubleChoiceSwitch;
  constructor() {}

  ngOnInit() {}

  switch(item: string) {
    if (this.switchValid(item)) {
      this.viewChange(item);
      this.change.emit(this.model);
    }
  }

  private switchValid(item: string) {
    if ((this.model.isFirstSwitchedOn && item === 'first') || (!this.model.isFirstSwitchedOn && item === 'second')) {
      return false;
    }
    return true;
  }

  private viewChange(item: string) {
    switch (item) {
      case 'first':
        this.state = 'inactive';
        this.model.isFirstSwitchedOn = true;
        break;
      case 'second':
        this.state = 'active';
        this.model.isFirstSwitchedOn = false;
        break;
    }
  }
}
