import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, forwardRef, Input, OnInit, Output, Renderer2 } from '@angular/core';
import { ControlValueAccessor, Validator, AbstractControl, ValidationErrors, NG_VALUE_ACCESSOR } from '@angular/forms';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { DropDownOption } from '../../../entity/dropDownOption';
import { MD2Service } from '../../../services/MD2/md2.service';
import { ArrayUtils } from '../../../utilities/array-utils';
import { HeroClass, MD2HeroInfo } from '../massive-darkness2.model';

@Component({
  selector: 'md2-hero-select',
  templateUrl: './md2-hero-select.component.html',
  styleUrls: ['./md2-hero-select.component.scss'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => MD2HeroSelectComponent),
      multi: true
    },
  ],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MD2HeroSelectComponent implements ControlValueAccessor, Validator {

  private _lastBlurValue: string;
  playerTabId: string;
  readonly: boolean = false;
  isRequired: boolean = false;
  heroOptions: DropDownOption[];
  @Input() id? = '';
  @Input() name = '';
  @Input() data: MD2HeroInfo;

  @Output() focus = new EventEmitter();
  @Output() blur = new EventEmitter<MD2HeroInfo>();

  @Input('readonly')
  public set input_readonly(value) {
    this.readonly = typeof value !== 'undefined' && value !== false;
  }
  @Input('isRequired')
  public set input_isRequired(value) {
    this.isRequired = typeof value !== 'undefined' && value !== false;
  }

  constructor(
    private elementRef: ElementRef,
    private renderer: Renderer2,
    private md2Service: MD2Service,
    private cdRef: ChangeDetectorRef
  ) {
    md2Service.refreshUI$.pipe(takeUntil(this.destroy$)).subscribe(result => {
      if (!this.cdRef['destroyed']) {
        this.cdRef.detectChanges();
      }
    });
  }
  private destroy$: Subject<void> = new Subject<void>();

  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }

  validate(control: AbstractControl): ValidationErrors {
    // if (this.required && (this.value == null || this.value == 0)) {
    //   return { 'currency': '' };
    // }
    return null;
  }
  registerOnValidatorChange?(fn: () => void): void {
  }
  onChange = (value: number) => { };
  onTouched = () => { };
  writeValue(obj: MD2HeroInfo): void {
    this.data = obj;
  }
  registerOnChange(fn: any): void {
    this.onChange = fn;
  }
  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }
  setDisabledState?(isDisabled: boolean): void {
    this.readonly = isDisabled;
  }

  ngOnInit() {

    this.heroOptions = ArrayUtils.ToDropDownOptions(this.md2Service.heros, h => h.playerInfo.tabId,
      hero => this.md2Service.heroFullName(hero));

  }

  ngAfterViewInit() {
    this.renderer.removeAttribute(this.elementRef.nativeElement, 'id')
  }
  onBlur() {
    if (this._lastBlurValue != this.playerTabId) {
      this._lastBlurValue = this.playerTabId;
      this.data = this.md2Service.heros.find(h => h.playerInfo.tabId == this.playerTabId);
      this.blur.emit(this.data);
    }
  }
}