import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Main } from 'src/app/models/main.model';
import { Mainsyntax } from 'src/app/models/main.model';
import { MainService } from 'src/app/services/main.service';
import { FormControl } from '@angular/forms';
import { Observable } from 'rxjs';
import { map, startWith } from 'rxjs/operators';
import { NotifierService } from "angular-notifier";

@Component({
  selector: 'app-main-details',
  templateUrl: './main-details.component.html',
  styleUrls: ['./main-details.component.scss']
})
export class MainDetailsComponent implements OnInit {
  mainsyntax = [
    { Attributes: [''], Id: "", Quantifier: false, Related_to_Subject: [], Subject: [], Verbs: [] }];
  mainsyntax11?: Mainsyntax = {
    Attributes: [],
    Quantifier: false,
    Related_to_Subject: [],
    Subject: [],
    Verbs: []
  };

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

  stateitemControl = new FormControl();
  stateitem: string[] = [];
  stateitemfilteredOptions: Observable<string[]>;
  stateitemControlisDivVisible = false

  statevalueControl = new FormControl();
  statevalue: string[] = [];
  statevaluefilteredOptions: Observable<string[]>;
  statevalueControlisDivVisible = false


  shallControl = new FormControl();
  shall: string[] = [];
  shallfilteredOptions: Observable<string[]>;

  verbControl = new FormControl();
  verb: string[] = [];
  verbfilteredOptions: Observable<string[]>;
  verbControlisDivVisible = true


  quantifierControl = new FormControl();
  quantifier: string[] = [];
  quantifierfilteredOptions: Observable<string[]>;
  quantifierControlisDivVisible = false

  numunitControl = new FormControl();
  numunit: string[] = [];
  numunitfilteredOptions: Observable<string[]>;
  numunitControlisDivVisible = false

  fifuintsysstatsetControl = new FormControl();
  fifuintsysstatset: string[] = [];
  fifuintsysstatsetfilteredOptions: Observable<string[]>;

  stsysconsetControl = new FormControl();
  stsysconset: string[] = [];
  stsysconsetfilteredOptions: Observable<string[]>;
  stsysconsetControlisDivVisible = false

  numericalisDivVisible = false


  public static id: any[] = [];
  private readonly notifier: NotifierService;
  mains?: Main[];

  currentmain: Main = {
    sys_fun_inter: "",
    state_item_before_verb: "",
    statevalue_before_verb: "",
    shall: "",
    verb: "",
    quantifier: "",
    numerical: 0,
    mumerical_units: "",
    flow_function_interface_item_system_state_stateset: "",
    statevalue_system_connection_stateset: "",
  };
  message = '';
  main = '';
  color_badge='danger'

  constructor(
    private mainService: MainService,
    private route: ActivatedRoute,
    private router: Router,
    notifierService: NotifierService) {
    this.notifier = notifierService;
    this.subjectsfilteredOptions = this.subjectsControl.valueChanges.pipe(
      startWith(""),
      map(value => this._filter(this.subjects, value))
    );
    this.stateitemfilteredOptions = this.stateitemControl.valueChanges.pipe(
      startWith(""),
      map(value => this._filter(this.stateitem, value))
    );
    this.statevaluefilteredOptions = this.statevalueControl.valueChanges.pipe(
      startWith(""),
      map(value => this._filter(this.statevalue, value))
    );
    this.shallfilteredOptions = this.shallControl.valueChanges.pipe(
      startWith(""),
      map(value => this._filter(this.shall, value))
    );
    this.verbfilteredOptions = this.verbControl.valueChanges.pipe(
      startWith(""),
      map(value => this._filter(this.verb, value))
    );
    this.quantifierfilteredOptions = this.quantifierControl.valueChanges.pipe(
      startWith(""),
      map(value => this._filter(this.quantifier, value))
    );
    this.numunitfilteredOptions = this.numunitControl.valueChanges.pipe(
      startWith(""),
      map(value => this._filter(this.numunit, value))
    );
    this.fifuintsysstatsetfilteredOptions = this.fifuintsysstatsetControl.valueChanges.pipe(
      startWith(""),
      map(value => this._filter(this.fifuintsysstatset, value))
    );
    this.stsysconsetfilteredOptions = this.stsysconsetControl.valueChanges.pipe(
      startWith(""),
      map(value => this._filter(this.stsysconset, value))
    );
  }

  ngOnInit(): void {
    this.getAllMain(this.route.snapshot.params.id);
    this.getchoices(this.route.snapshot.params.gb);
    this.getmainchoices(this.route.snapshot.params.gb);
  }

  ngDoCheck() {
    this.color_badge='danger'
    this.dis();
  }

  dis(): any {
    //Check for each M1-M16
    for (let x = 0; x < this.mainsyntax.length; x++) {
      for (let s = 0; s < this.mainsyntax[x].Subject.length; s++) {
        if (this.mainsyntax[x].Subject[s] == this.subjectsControl.value ? (this.subjectsControl.value.slice(0, this.subjectsControl.value.indexOf(':'))).replace(/\s/g, "") : this.subjectsControl.value) {
          for (let v = 0; v < this.mainsyntax[x].Verbs.length; v++) {
            if (this.mainsyntax[x].Verbs[v] == (this.verbControl.value.split(" : ").pop()).replace(/\s/g, "")) {
              for (let a = 0; a < this.mainsyntax[x].Attributes.length; a++) {
                if (this.mainsyntax[x].Attributes[a] == (this.fifuintsysstatsetControl.value.slice(0, this.fifuintsysstatsetControl.value.indexOf(':'))).replace(/\s/g, "")) {
                  if (this.mainsyntax[x].Related_to_Subject.length > 0) {
                    this.stateitemControlisDivVisible = true
                    for (let r = 0; r < this.mainsyntax[x].Related_to_Subject.length; r++) {
                      if (this.mainsyntax[x].Related_to_Subject[r] == "StateValue") { this.statevalueControlisDivVisible = true; }
                    }
                  }
                  if (this.mainsyntax[x].Quantifier) {
                    this.quantifierControlisDivVisible = true;
                    this.numericalisDivVisible = true;
                    //numerical value
                    this.numunitControlisDivVisible = true;
                    //add the numunit data
                  }
                  if (this.mainsyntax[x].Attributes.includes('StateValue') || this.mainsyntax[x].Attributes.includes('System') || this.mainsyntax[x].Attributes.includes('Connection') || this.mainsyntax[x].Attributes.includes('StateSet')) {
                    if (!this.mainsyntax[x].Id.includes('M14') && !this.mainsyntax[x].Id.includes('M16')) {
                      this.stsysconsetControlisDivVisible = true;
                    }
                    //add the connection data
                  }
                  this.main = this.mainsyntax[x].Id
                  this.color_badge='success'
                  return 1;
                }
              }
            }
          }
        }
      }
      //Related to System
      this.stateitemControlisDivVisible = false;
      this.statevalueControlisDivVisible = false;
      //Quantifier
      //this.quantifierControl.markAsUntouched();
      this.quantifierControlisDivVisible = false;
      //numerical value
      this.numunitControlisDivVisible = false;
      this.numericalisDivVisible = false;
      // Extra Attribute
      this.stsysconsetControlisDivVisible = false;
      this.main = "No boilerplate with this syntax"
    }
  }

  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));
  }

  getAllMain(id: string): void {
    this.mainService.getAll(id)
      .subscribe(
        data => {
          MainDetailsComponent.id.length = 0;
          this.mains = data;
          for (var val of data) {
            MainDetailsComponent.id.push(val.id);
            this.getMain(id, val.id);
          }
        },
        error => {
          console.log(error);
        });
  }
  getMain(main: any, id: string): void {
    //PrefixDetailsComponent.id = id;
    this.mainService.get(main, id)
      .subscribe(
        data => {
          this.currentmain = data;
          this.subjectsControl.setValue(this.currentmain.sys_fun_inter);
          this.stateitemControl.setValue(this.currentmain.state_item_before_verb);
          this.statevalueControl.setValue(this.currentmain.statevalue_before_verb);
          this.shallControl.setValue(this.currentmain.shall);
          this.verbControl.setValue(this.currentmain.verb);
          this.quantifierControl.setValue(this.currentmain.quantifier);
          // num
          this.numunitControl.setValue(this.currentmain.mumerical_units);
          this.fifuintsysstatsetControl.setValue(this.currentmain.flow_function_interface_item_system_state_stateset);
          this.stsysconsetControl.setValue(this.currentmain.statevalue_system_connection_stateset);
        },
        error => {
          console.log(error);
        });
  }

  updateMain(): void {
    this.currentmain.sys_fun_inter = this.subjectsControl.value;
    if (this.stateitemControlisDivVisible) { this.currentmain.state_item_before_verb = this.stateitemControl.value; } else { this.currentmain.state_item_before_verb = '' }
    if (this.statevalueControlisDivVisible) { this.currentmain.statevalue_before_verb = this.statevalueControl.value; } else { this.currentmain.statevalue_before_verb = '' }
    this.currentmain.shall = this.shallControl.value;
    this.currentmain.verb = this.verbControl.value;
    if (this.quantifierControlisDivVisible) { this.currentmain.quantifier = this.quantifierControl.value; } else { this.currentmain.quantifier = '' }
    //num
    if (this.numericalisDivVisible) { this.currentmain.mumerical_units = this.numunitControl.value; } else { this.currentmain.mumerical_units = '' }
    this.currentmain.flow_function_interface_item_system_state_stateset = this.fifuintsysstatsetControl.value;
    if (this.stsysconsetControlisDivVisible) { this.currentmain.statevalue_system_connection_stateset = this.stsysconsetControl.value; } else { this.currentmain.statevalue_system_connection_stateset = '' }


    for (let i = 0; i < MainDetailsComponent.id.length; i++) {
      this.mainService.update(this.route.snapshot.params.id, MainDetailsComponent.id[i], this.currentmain)
        .subscribe(
          response => {
            this.message = response.message;
          },
          error => {
            this.notifier.notify("warning", ("MAIN " + JSON.stringify(error["error"]["detail"])));
          });
    }


  }

  getmainchoices(main: any): void {
    this.mainService.getmain(main)
      .subscribe(
        data => {
          //get Subject
          this.getsubject(JSON.parse(data[0].system_choices));
          this.getsubject(JSON.parse(data[0].function_choices));
          this.getsubject(JSON.parse(data[0].inteface_choices));
          //get State Item
          this.getstateitem(JSON.parse(data[0].state_choices));
          this.getstateitem(JSON.parse(data[0].item_choices));
          //get statevalue
          this.getstatevalue(JSON.parse(data[0].state_value_choices));
          //get verd
          this.getverb(JSON.parse(data[0].main_verb_choices));
          //get quantifier
          this.getquantifier(JSON.parse(data[0].quantifier_choices));
          // get fifuintsysstatset
          this.getfifuintsysstatset(JSON.parse(data[0].flow_choices));
          this.getfifuintsysstatset(JSON.parse(data[0].function_choices));
          this.getfifuintsysstatset(JSON.parse(data[0].inteface_choices));
          this.getfifuintsysstatset(JSON.parse(data[0].item_choices));
          this.getfifuintsysstatset(JSON.parse(data[0].system_choices));
          this.getfifuintsysstatset(JSON.parse(data[0].state_choices));
          this.getfifuintsysstatset(JSON.parse(data[0].state_set_choices));
          //stsysconset
          this.getstsysconset(JSON.parse(data[0].state_set_choices));
          this.getstsysconset(JSON.parse(data[0].system_choices));
          this.getstsysconset(JSON.parse(data[0].connection_choices));
          this.getstsysconset(JSON.parse(data[0].state_value_choices));
          // number_unit_choices
          this.getnumunit(JSON.parse(data[0].number_unit_choices));
        },
        error => {
          console.log(error);
        });
  }


  getsubject(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]));
      }
    }
  }

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


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

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

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

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

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

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

  getchoices(id: string): void {
    this.mainService.getmainsyntax(id)
      .subscribe(
        data => {
          this.mainsyntax = data
          //console.log(this.mainsyntax);

        },
        error => {
          console.log(error);
        });

    this.mainService.getshall()
      .subscribe(
        data => {
          for (let x = 0; x < data.length; x++) {
            if (this.shall.indexOf(data[x][1]) == -1) {
              this.shall.push(data[x][1]);
            }
          }
        },
        error => {
          console.log(error);
        });
  }
}


