import { Component, OnInit, ViewChild } from '@angular/core';
import { Boilerplate } from 'src/app/models/boilerplate.model';
import { BoilerplateData } from 'src/app/models/boilerplate.model';
import { InferenceResults } from 'src/app/models/boilerplate.model';
import { BoilerplateService } from 'src/app/services/boilerplate.service';
import { PrefixService } from 'src/app/services/prefix.service';
import { ActivatedRoute, Router } from '@angular/router';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { EChartsOption } from 'echarts';
import { NotifierService } from "angular-notifier";



@Component({
  selector: 'app-boilerplate-list',
  templateUrl: './boilerplate-list.component.html',
  styleUrls: ['./boilerplate-list.component.scss']
})


export class BoilerplateListComponent implements OnInit {

  chartOption: EChartsOption = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '5%',
      left: 'center'
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        data: [
          { value: 0, name: '1' },
          { value: 0, name: '2' },
          { value: 0, name: '3' },
          { value: 0, name: '4' },
          { value: 0, name: '5' }]
      }
    ],
  };
  private readonly notifier: NotifierService;
  boilerplates?: Boilerplate[];
  boilerplatesdata?: BoilerplateData[];
  currentBoilerplate?: Boilerplate;
  currentBoilerplatedata?: BoilerplateData;
  currentInfer?: InferenceResults = {
    infer_group_of_boilerplate: "",
    inference_data: "",
  }
  currentIndex = -1;
  title = '';
  displayedColumns: string[] = ['id', 'title', 'has_prefix', 'has_main', 'has_suffix', 'action'];
  newdisplayedColumns: string[] = ['id', 'title_data', 'prefix_data', 'main_data', 'suffix_data', 'action'];
  dataSource: Boilerplate[] = [{}];
  thenewdataSource: BoilerplateData[] = [{}];
  newdataSource = new MatTableDataSource(this.thenewdataSource);
  infer: InferenceResults[] = [{}];
  //when inference button is pressed
  showSpinner = false;
  exporting = false;

  list_of_inference_metrics = ["IncompleteRequirement", "AmbiguousRequirement", "InconsistentRequirement", "NoisyRequirement", "OpaqueRequirement", "RedundantRequirement"]

  @ViewChild(MatPaginator) paginator = this.newdataSource.paginator;


  dataofboilerplates: any[] = [];
  aprefix: any[] = [];
  main: any;
  suffix: any;

  constructor(private boilerplateService: BoilerplateService, private prefixService: PrefixService, private route: ActivatedRoute,
    private router: Router, notifierService: NotifierService) {
    this.notifier = notifierService;
  }


  ngOnInit(): void {
    this.retrieveBoilerplates();
    this.retrieve();
    this.getInfer();
  }

  retrieveBoilerplates(): void {
    this.boilerplateService.getAll(this.route.snapshot.params.gb)
      .subscribe(
        data => {
          this.boilerplates = data;
          this.dataSource = data;
        },
        error => {
          console.log(error);
        });

  }


  retrieve(): void {
    this.boilerplateService.getAllData(this.route.snapshot.params.gb)
      .subscribe(
        data => {
          this.boilerplatesdata = data;
          this.thenewdataSource = data;
          this.newdataSource = new MatTableDataSource(this.thenewdataSource);
          this.newdataSource.paginator = this.paginator;
          //console.log(data)
        },
        error => {
          console.log(error);
        });

  }

  refreshList(): void {
    this.retrieveBoilerplates();
    this.currentBoilerplate = undefined;
    this.currentIndex = -1;
  }

  setActiveBoilerplate(boilerplate: Boilerplate, index: number): void {
    this.currentBoilerplate = boilerplate;
    this.currentIndex = index;
  }


  SearchTitle(): void {
    if (this.title != '') {
      this.boilerplateService.findByTitle(this.route.snapshot.params.gb, this.title)
        .subscribe(
          data => {
            this.boilerplates = data;
            this.dataSource = data;
            //console.log(data);
          },
          error => {
            console.log(error);
          });

    }
    else {
      this.retrieveBoilerplates();
    }
  }
  GetRoute(): void {
    this.router.navigate(['/groupboilerplates/' + this.route.snapshot.params.gb + '/boilerplates/add-boilerplate'])
  }
  GetRoutedit(id: any): void {
    this.router.navigate(['/groupboilerplates/' + this.route.snapshot.params.gb + '/boilerplates' + id])
  }

  getInfer(): void {
    this.boilerplateService.getAllInfer(this.route.snapshot.params.gb)
      .subscribe(
        data => {
          console.log(data);
          this.currentInfer = data[0];
          this.infer = data;
          if (data[0]) {
            const obj = JSON.parse(this.currentInfer['inference_data'].replace(/'/g, "\""))
            var final = []
            for (let i of this.list_of_inference_metrics) {
              if (obj[i] != undefined) {

                final.push({ value: obj[i].length, name: i })
              }

            }
          }
          //console.log(final);
          this.chartOption.series = [{
            type: 'pie',
            radius: ['40%', '70%'],
            data: final,
          }]

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

  }

  updateInfer(id: any): void {
    this.showSpinner = !this.showSpinner;
    this.exporting = !this.exporting
    this.boilerplateService.inferUpdate(this.route.snapshot.params.gb, id, this.currentInfer)
      .subscribe(
        data => {
          this.currentInfer = data[0];
          //this.infer = data;
          this.showSpinner = !this.showSpinner;
          this.exporting = !this.exporting;
          location.reload();
        },
        error => {
          console.log(error);
          this.showSpinner = !this.showSpinner;
          this.exporting = !this.exporting
          this.notifier.notify("warning", (JSON.stringify(error["error"]["detail"])));
        });
  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.newdataSource.filter = filterValue.trim().toLowerCase();
  }

  get_metrics(i: any): any {
    if (this.currentInfer?.inference_data) {
      const obj = JSON.parse(this.currentInfer['inference_data'].replace(/'/g, "\""))
      if (obj[i]) {
        return obj[i]
      }
    }
    return 0
  }
  getnumreq(): any {
    return this.boilerplatesdata?.length
  }

  getincreq(): any {
    return this.get_metrics('IncompleteRequirement').length;
  }

}
