import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Suffix } from 'src/app/models/suffix.model';
import { SuffixService } from 'src/app/services/suffix.service';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
import { NotifierService } from "angular-notifier";


@Component({
  selector: 'app-suffix-details',
  templateUrl: './suffix-details.component.html',
  styleUrls: ['./suffix-details.component.scss']
})
export class SuffixDetailsComponent implements OnInit {

  suffixControl = new FormControl();
  suffix: string[] = [];
  suffixfilteredOptions: Observable<string[]>;

  mumerical_unitsControl = new FormControl();
  mumerical_units: string[] = [];
  mumerical_unitsfilteredOptions: Observable<string[]>;

  flowControl = new FormControl();
  flow: string[] = [];
  flowfilteredOptions: Observable<string[]>;
  flowControlisDivVisible = false

  public static id: any[] = [];
  private readonly notifier: NotifierService;
  suffixs?: Suffix[];

  currentsuffix: Suffix = {
    s_choices: "",
    numerical: 0,
    mumerical_units: "",
    flow: "",
  };
  message = '';

  constructor(
    private suffixService: SuffixService,
    private route: ActivatedRoute,
    private router: Router,
    notifierService: NotifierService) {
    this.notifier = notifierService;
    this.suffixfilteredOptions = this.suffixControl.valueChanges.pipe(
      startWith(""),
      map(value => this._filter(this.suffix, value))
    );
    this.mumerical_unitsfilteredOptions = this.mumerical_unitsControl.valueChanges.pipe(
      startWith(""),
      map(value => this._filter(this.mumerical_units, value))
    );
    this.flowfilteredOptions = this.flowControl.valueChanges.pipe(
      startWith(""),
      map(value => this._filter(this.flow, value))
    );

  }

  ngOnInit(): void {
    //this.getchoices();
    this.getflowchoices(this.route.snapshot.params.gb);
    console.log('aaa', this.route.snapshot.params.gb);

    this.getAllSuffix(this.route.snapshot.params.id);
  }


  displayFn(option: string): string {
    if (option != null) {
      let x = option.split(" : ");
      if ((x[x.length - 2] == "") || (x[x.length - 1] == "")) { return ""; }
      return (x[x.length - 1]);
    }
    return "";
  }

  showflow(option: string): boolean {
    this.flowControlisDivVisible = false
    if (option != null) {
      let x = option.split(" : ");
      if ((x[x.length - 2] == "") || (x[x.length - 1] == "")) { return false; }
      if (x[x.length - 2] == 'EventRelated' || x[x.length - 2] == 'TimeRangeRelated' || x[x.length - 2] == 'ExecutionRelated') { this.flowControlisDivVisible = true; return true; }
    }
    return false;
  }

  private _filter(data: string[], value: string): string[] {
    const filterValue = value.toLowerCase();
    return data.filter(option => option.toLowerCase().includes(filterValue));
  }


  getAllSuffix(id: string): void {
    this.suffixService.getAll(id)
      .subscribe(
        data => {
          SuffixDetailsComponent.id.length = 0;
          this.suffixs = data;
          //console.log(data)
          for (var val of data) {
            this.getSuffix(id, val.id);
            SuffixDetailsComponent.id.push(val.id);
            //console.log(val.id)
          }
        },
        error => {
          console.log(error);
        });
  }

  getSuffix(main: any, id: string): void {
    //PrefixDetailsComponent.id = id;
    this.suffixService.get(main, id)
      .subscribe(
        data => {
          this.currentsuffix = data;
          //console.log(data)
          this.suffixControl.setValue(this.currentsuffix.s_choices);
          this.mumerical_unitsControl.setValue(this.currentsuffix.mumerical_units);
          this.flowControl.setValue(this.currentsuffix.flow);
        },
        error => {
          console.log(error);
        });
  }


  updateSuffix(): void {
    this.currentsuffix.s_choices = this.suffixControl.value;
    this.currentsuffix.mumerical_units = this.mumerical_unitsControl.value;
    if (this.flowControlisDivVisible) { this.currentsuffix.flow = this.flowControl.value; } else { this.currentsuffix.flow = '' }
    for (let i = 0; i < SuffixDetailsComponent.id.length; i++) {
      this.suffixService.update(this.route.snapshot.params.id, SuffixDetailsComponent.id[i], this.currentsuffix)
        .subscribe(
          response => {
            this.message = response.message;
          },
          error => {
            this.notifier.notify("warning", ("SUFFIX " + JSON.stringify(error["error"])));
          });
    }
  }


  getflowchoices(prefix_group: any): void {
    this.suffixService.getsuffixflow(prefix_group)
      .subscribe(
        data => {
          //set flow choices
          this.setflow(JSON.parse(data[0].flow_choices));
          this.setflow(JSON.parse(data[0].function_choices));
          this.setsuffix(JSON.parse(data[0].suffix_choices));
          this.setmumerical_units(JSON.parse(data[0].number_unit_choices));
        },
        error => {
          console.log(error);
        });
  }
  setflow(strIntoObj: any): void {
    for (let x = 0; x < strIntoObj.length; x++) {
      if (this.flow.indexOf(strIntoObj[x][1]) == -1) {
        this.flow.push((strIntoObj[x][1]));
      }
    }
  }

  setsuffix(strIntoObj: any): void {
    for (let x = 0; x < strIntoObj.length; x++) {
      if (this.suffix.indexOf(strIntoObj[x][1]) == -1) {
        this.suffix.push((strIntoObj[x][1]));
      }
    }
  }

  setmumerical_units(strIntoObj: any): void {
    for (let x = 0; x < strIntoObj.length; x++) {
      if (this.mumerical_units.indexOf(strIntoObj[x][1]) == -1) {
        this.mumerical_units.push((strIntoObj[x][1]));
      }
    }
  }



}


/*this.suffixService.getflow()
      .subscribe(
        data => {
          for (let x = 0; x < data.length; x++) {
            if (this.flow.indexOf(data[x][1]) == -1) {
              this.flow.push(data[x][1]);
            }
          }
        },
        error => {
          console.log(error);
        });*/