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


@Component({
  selector: 'app-prefix-details',
  templateUrl: './prefix-details.component.html',
  styleUrls: ['./prefix-details.component.scss']

})
export class PrefixDetailsComponent implements OnInit {
  simpleprefixControl = new FormControl();
  simpleprefix: string[] = [];
  simpleprefixfilteredOptions: Observable<string[]>;

  subjectsControl = new FormControl();
  subjects: string[] = [];
  subjectsfilteredOptions: Observable<string[]>;

  verbsControl = new FormControl();
  verbs: string[] = [];
  verbsfilteredOptions: Observable<string[]>;

  objectsControl = new FormControl();
  objects: string[] = [];
  objectsfilteredOptions: Observable<string[]>;

  logic_conControl = new FormControl();
  logic_con: string[] = [];
  logic_confilteredOptions: Observable<string[]>;


  public static id: any[] = [];
  private readonly notifier: NotifierService;
  prefixs?: Prefix[];

  //for the moment only one prefix can showed/updates
  currentprefix: Prefix = {
    prefix_group: "",
    prefix: "",
    system_fun_item: "",
    state_or_verb: "",
    item_function_flow_statevalue: "",
    logical_expression: "",
    logic_connective: "",
    simple_prefix: "",
  };
  message = '';


  constructor(private prefixService: PrefixService, private route: ActivatedRoute,
    private router: Router, notifierService: NotifierService) {
      this.notifier = notifierService;
    this.simpleprefixfilteredOptions = this.simpleprefixControl.valueChanges.pipe(
      startWith(""),
      map(value => this._filter(this.simpleprefix, value))
    );
    this.subjectsfilteredOptions = this.subjectsControl.valueChanges.pipe(
      startWith(""),
      map(value => this._filter(this.subjects, value))
    );
    this.verbsfilteredOptions = this.verbsControl.valueChanges.pipe(
      startWith(""),
      map(value => this._filter(this.verbs, value))
    );
    this.objectsfilteredOptions = this.objectsControl.valueChanges.pipe(
      startWith(""),
      map(value => this._filter(this.objects, value))
    );
    this.logic_confilteredOptions = this.logic_conControl.valueChanges.pipe(
      startWith(""),
      map(value => this._filter(this.logic_con, value))
    );
  }

  ngOnInit(): void {
    this.getchoices(this.route.snapshot.params.gb);
    this.getAllPrefix(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 "";
  }

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

  getAllPrefix(id: string): void {
    this.prefixService.getAll(id)
      .subscribe(
        data => {
          PrefixDetailsComponent.id.length = 0;
          this.prefixs = data;
          //console.log(data);
          for (var val of data) {
            this.getPrefix(id, val.id);
            PrefixDetailsComponent.id.push(val.id);
          }
        },
        error => {
          console.log(error);
        });
  }

  getPrefix(prefix: any, id: string): void {
    //PrefixDetailsComponent.id = id;
    this.prefixService.get(prefix, id)
      .subscribe(
        data => {
          this.currentprefix = data;
          //console.log(data)
          this.simpleprefixControl.setValue(this.currentprefix.prefix);
          this.subjectsControl.setValue(this.currentprefix.system_fun_item);
          this.verbsControl.setValue(this.currentprefix.state_or_verb);
          this.objectsControl.setValue(this.currentprefix.item_function_flow_statevalue);
          this.logic_conControl.setValue(this.currentprefix.logic_connective);
        },
        error => {
          console.log(error);
        });
  }


  updatePrefix(): any {
    this.currentprefix.prefix = this.simpleprefixControl.value;
    this.currentprefix.system_fun_item = this.subjectsControl.value;
    this.currentprefix.state_or_verb = this.verbsControl.value;
    this.currentprefix.item_function_flow_statevalue = this.objectsControl.value;
    this.currentprefix.logic_connective = this.logic_conControl.value;
    for (let i = 0; i < PrefixDetailsComponent.id.length; i++) {
      this.prefixService.update(this.route.snapshot.params.id, PrefixDetailsComponent.id[i], this.currentprefix)
        .subscribe(
          response => {
            this.message = response.message;
          },
          error => {
            this.notifier.notify("warning", ("PREFIX " + JSON.stringify(error["error"]['detail'])));
          });
    }
  }


  getchoices(prefix_group: any): void {
    this.prefixService.getsimpleprefix(prefix_group)
      .subscribe(
        data => {
          //set prefix choices
          this.setprefix(JSON.parse(data[0].prefix_choices));
          //set verb choices
          this.setverb(JSON.parse(data[0].prefix_verb_choices));
          //set subject choices
          this.setsubject(JSON.parse(data[0].item_choices));
          this.setsubject(JSON.parse(data[0].system_choices));
          this.setsubject(JSON.parse(data[0].function_choices));
          //set object choices
          this.setobject(JSON.parse(data[0].item_choices));
          this.setobject(JSON.parse(data[0].flow_choices));
          this.setobject(JSON.parse(data[0].function_choices));
          this.setobject(JSON.parse(data[0].state_value_choices));
          //set logic connectivity choices
          this.setlogcon(JSON.parse(data[0].prefix_logcon_choices));
        },
        error => {
          console.log(error);
        });
  }

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

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

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

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

  }

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

}