import {Component, forwardRef, OnInit} from '@angular/core';
import {EventService, EventType} from "../../services/event.service";
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms";

const FIT_EVENT_TYPES_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => FitEventTypesComponent),
  multi: true,
};

@Component({
  selector: 'app-fit-event-types',
  templateUrl: './fit-event-types.component.html',
  styleUrls: ['./fit-event-types.component.scss'],
  providers: [FIT_EVENT_TYPES_VALUE_ACCESSOR],

})
export class FitEventTypesComponent implements OnInit, ControlValueAccessor {

  types: EventType[];
  selected: any;

  private onChange: Function;
  private onTouched: Function;
  public value: string;

  constructor(private eventService: EventService) {
    this.onChange = (_: any) => { };
    this.onTouched = () => { };
  }

  ngOnInit() {
    this.eventService.findAllEventTypes()
      .subscribe(value => {
          this.types = [{ id: -1, name: 'Minden Típus', theme: '' }].concat( value);
          this._setValue(this.types[0].id);
        }
      );
  }

  private _setValue(value) {
    this.value = value;
    this.onChange(this.value);
    this.onTouched();
  }

  setValue($event: Event) {
    this._setValue((<any>$event.target).value);
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean): void {
  }

  writeValue(obj: any): void {
    this.value = obj;
  }
}
