import { LayoutService } from './../../core/layout.service';
import { Subscription, Observable } from 'rxjs';
import { AttacksFeatureState, AttacksState } from './../store/attacks.redurecs';
import { Store } from '@ngrx/store';
import { FormControl, Validators, AbstractControl } from '@angular/forms';
import { FormGroup } from '@angular/forms';
import { Component, OnInit, OnDestroy, Inject } from '@angular/core';
import { AttackAutocomplete } from '../model/attack-autocomplete.model';
import { Attack } from '../model/attack.model';
import { RequestAttacksListAction } from '../store/attacks.actions';
import { map } from 'rxjs/operators';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';

@Component({
  selector: 'app-related-attack-edit',
  templateUrl: './related-attack-edit.component.html',
  styleUrls: ['./related-attack-edit.component.scss']
})
export class RelatedAttackEditComponent implements OnInit, OnDestroy {

  private forbiddenIds: number[] = [];

  private autocompleteData: AttackAutocomplete[] = [];
  public attacks: Observable<AttackAutocomplete[]>;

  private storeSubscription: Subscription;

  private isWebView: Boolean = false;
  private webViewSubscription: Subscription;

  relatedAttackForm: FormGroup = new FormGroup({
    'relatedAttackId': new FormControl(null, [Validators.required, this.selectedAttackValidator.bind(this)]),
    'note': new FormControl(null, Validators.maxLength(200))
  })

  constructor(@Inject(MAT_DIALOG_DATA) private data: any, private store: Store<AttacksFeatureState>, private layoutService: LayoutService) {
    if (data.forbiddenIds){
      this.forbiddenIds = data.forbiddenIds;
    }
    this.webViewSubscription = this.layoutService.isWebView.subscribe(
      (isWebView: boolean) => { this.isWebView = isWebView; }
    )
    this.storeSubscription = this.store.select('attacks').subscribe(
      (state: AttacksState) => {
        let attacks = state.attacks;
        if (attacks === null)
          this.store.dispatch(new RequestAttacksListAction());
        else{
          this.autocompleteData = attacks.map(
            (attack: Attack) => { return new AttackAutocomplete(attack.id, attack.country, attack.city, attack.date) }
          ).filter((attack: AttackAutocomplete) => { return !this.forbiddenIds.includes(attack.id) });
          this.attacks = this.relatedAttackForm.get('relatedAttackId').valueChanges.pipe(
            map(inputValue => this.filterAutoComplete(inputValue))
          );
        }
      }
    );
  }

  ngOnInit() {
  }

  ngOnDestroy(){
    this.webViewSubscription.unsubscribe();
    this.storeSubscription.unsubscribe();
  }

  displayAttackFn(attack?: AttackAutocomplete){
    return attack ? attack.getLabel(!this.isWebView) : undefined;
  }

  selectedAttackValidator(control: AbstractControl){
    let inputValue = control.value;
    let attack: AttackAutocomplete = this.autocompleteData.find((attack: AttackAutocomplete) => { return attack === inputValue});
    return attack ? null : { selected: true };
  }

  private filterAutoComplete(input: String){
    if (typeof input === "string"){
      let inputValues: String[] = input.split(",");
      inputValues = inputValues.map(inputValue => inputValue.trim().toLocaleLowerCase());
      return this.autocompleteData.filter((attack: AttackAutocomplete) => {
        return inputValues.every((inputValue: string) => { 
          return attack.city.toLocaleLowerCase().includes(inputValue) ||
          attack.country.toLocaleLowerCase().includes(inputValue) ||
          attack.date.toLocaleLowerCase().includes(inputValue);
        })
      });
    }
  }

}
