import { Component, OnInit } from '@angular/core';
import { LoginService } from '../services/login.service';
import { ApiService } from '../services/api.service';
import { Chart } from 'chart.js';


interface KeyInterface {
  id: string;
  count: number;
  active: boolean;
}

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

  keys: KeyInterface[] = [];
  isActiveKey: { [key: string]: boolean } = {};  // Object to check if key is currently active
  myChart: Chart;

  constructor(
    public login: LoginService,
    public api: ApiService
  ) { }

  ngOnInit() {
    // Fetch all available groups  
    this.fetchData('/material/groups', data => this.createGroup(data));
  }

  // Api access with callback
  async fetchData(URL: string, processor: any) {
    this.api.get(URL, (sData, err, headers) => {
      processor(sData);
    });
  }

  // Fill interface with data
  createGroup(data: any) {
    let temp: KeyInterface[] = [];

    for (var i = 0; i < data.length; i++) {
      temp.push({ id: data[i], count: 0, active: false });
    }
    this.keys = temp; // invoke update in rb-multiselect
    this.initChart();

    // Only neccesary if keys get preselected
    //this.calcFieldSelectKeys();

    // Fetch all samples populated with according group
    this.getSamples();
  }

  // Iterate through active keys to assemble an api request for the required data
  getSamples() {
    let query = '/samples?status%5B%5D=validated&status=new&filters%5B%5D=%7B%22mode%22%3A%22in%22%2C%22field%22%3A%22material.group%22%2C%22values%22%3A%5B';
    let temp = '';
    this.keys.forEach(key => {
      temp += key.active ? '%22' + key.id.split("%").join("%25") + '%22%2C' : ""; // replace split().join() with replaceAll() 
    });
    if (temp === '') {
      this.countSamples('');
    } else {
      query = query + temp.substr(0, temp.length - 3) + '%5D%7D&fields%5B%5D=material.group';
      this.fetchData(query, data => this.countSamples(data));
    }
  }

  // Loop through samples and count
  countSamples(data: any) {
    this.keys.map(key => key.count = 0);
    for (var i = 0; i < data.length; i++) {
      this.keys.forEach(key => {
        if (key.id === data[i].material.group) {
          key.count += 1;
        }
      });
    }
    this.updateGraph();
  }

  // Preset select
  calcFieldSelectKeys() {
    this.keys.forEach(key => {
      this.isActiveKey[key.id] = key.active;
    });
  }

  // Update keys based on select
  updateGroups(activeKeys: any) {
    this.keys.forEach(key => {
      if (activeKeys.hasOwnProperty(key.id)) {
        key.active = activeKeys[key.id];
      }
    });
    this.getSamples();
  }

  // Get data for graph based on active keys
  updateGraph() {
    let nameList: string[] = [];
    let dataList: number[] = [];

    this.keys.forEach(key => {
      if (key.active) {
        nameList.push(key.id);
        dataList.push(key.count);
      }
    })
    this.myChart.data.labels = nameList;
    this.myChart.data.datasets[0].data = dataList;
    this.myChart.update();
  }

  // Initialize graph
  async initChart() {
    this.myChart = new Chart("myChart", {
      type: 'bar',
      data: {
        labels: [],
        datasets: [{
          label: 'Number of samples per group',
          data: [],
          backgroundColor: 'rgba(0, 86, 145, 1)'
        }]
      },
      options: {
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        }
      }
    });
  }
}
