import { Component, Inject, OnInit } from '@angular/core';
import { ProgressBarMode } from '@angular/material/progress-bar';
import { ThemePalette } from '@angular/material/core';
import { Chart } from 'node_modules/chart.js';
import { MatDialog, MAT_DIALOG_DATA } from '@angular/material/dialog';
@Component({
  selector: 'app-workflow-detail-advance',
  templateUrl: './workflow-detail-advance.component.html',
  styleUrls: ['./workflow-detail-advance.component.css'],
})
export class WorkflowDetailAdvanceComponent implements OnInit {
  color: ThemePalette = 'primary';
  mode: ProgressBarMode = 'determinate';
  value = 50;
  tasksArrayComplete: any[] = [];
  tasksValidate: any = [];
  percentageTasks: any = [];
  colorsTasks: any[] = [];
  bufferValue = 75;
  dataSetsAux: any[] = [];
  percentageWorklfowAux = 0;
  arrayColors: any[] = [
    '#407CF7',
    '#73E8FF',
    '#49EBAF',
    '#37D445',
    '#A8F740',
    '#FFA670',
    '#E88466',
    '#FF867C',
    '#E86682',
    '#FF70D6',
    '#FFFF8B',
    '#E8B766',
    '#FF887D',
    '#BD66E8',
    '#70A2FF',
  ];
  constructor(@Inject(MAT_DIALOG_DATA) public dataDialog: any) {
    console.log(this.dataDialog);
  }

  ngOnInit(): void {
    this.transformDataArrays();

    console.log(this.calculatedPercentageWorkflow());

    const porcentageSubWorkflow =
      isNaN(this.getPercentageTaskWithWorkflow()) == true
        ? ''
        : 'Porcentaje de avance del subworkflow de la tarea ' +
          this.getPercentageTaskWithWorkflow() +
          ' %';

    const status = this.tasksValidate;
    const percentageWorklfow = this.calculatedPercentageWorkflow();

    let myChart = new Chart('myChart', {
      type: 'bar',
      data: {
        labels: ['Secuencias'],
        datasets: this.dataSetsAux,
      },
      options: {
        scales: {
          y: {
            beginAtZero: true,
          },
        },
        plugins: {
          tooltip: {
            callbacks: {
              beforeTitle: function (context) {
                return `${context[0].dataset.label}`;
              },

              title: function (context) {
                return 'Secuencia - ' + status[context[0].datasetIndex];
              },

              label: function (context: any) {
                return 'Porcentaje de avance: ' + context.dataset.data[0] + '%';
              },

              /*               afterTitle: function (context) {
                return (
                  'Porcentaje de avance del subworkflow de la tarea ' +
                  porcentageSubWorkflow +
                  '%'
                );
              }, */
            },
          },
          legend: {
            labels: {
              // This more specific font property overrides the global property
              font: {
                size: 12,
              },
            },
          },
          title: {
            display: true,
            text: [
              'Secuencia actual: ' + this.dataDialog.sequence,
              'Porcentaje de avance de la solicitud ' +
                Math.round(percentageWorklfow) +
                '%',
              porcentageSubWorkflow,
            ],
            font: {
              size: 15,
            },
          },
        },
        responsive: true,
      },
    });
  }

  private transformDataArrays() {
    let indexColor = 0;
    this.tasksValidate = this.dataDialog.workflow.tasks.map((task: any) => {
      if (task.status == 'Completed') {
        return `Completada`;
      } else if (task.status == 'Executed') {
        return `En ejecución`;
      } else if (task.status == 'Pending') {
        return `Pendiente`;
      } else if (!task.isAvailable) {
        return `Inhabilitada`;
      } else if (task.status == 'Canceled') {
        return `Cancelada`;
      }
      return null;
    });

    this.percentageTasks = this.dataDialog.workflow.tasks.map((task: any) => {
      if (task.status == 'Completed') {
        return 100;
      } else if (task.status == 'Executed') {
        return 50;
      } else if (task.status == 'Pending') {
        return 5;
      } else if (!task.isAvailable) {
        return 5;
      } else if (task.status == 'Canceled') {
        return 10;
      }
      return 0;
    });

    for (
      let index = 0;
      index < this.dataDialog.workflow.tasks.length;
      index++
    ) {
      let objDataSet = {
        label: 'Secuencia ' + this.dataDialog.workflow.tasks[index].sequence,
        data: [this.percentageTasks[index]],
        backgroundColor: this.arrayColors[index],
      };

      indexColor =
        index == this.arrayColors.length ? (indexColor = 0) : indexColor + 1;

      this.dataSetsAux.push(objDataSet);
    }
  }

  private getPercentageTaskWithWorkflow() {
    let cont = 0;
    let sizeWorkflowLevel2: number = 0;

    let positionTaskCurrent = this.dataDialog.workflow.tasks.findIndex(
      (object: any) => {
        return object.sequence == this.dataDialog.sequence;
      }
    );

    let arrTaskCurrent: any[] =
      this.dataDialog.workflow.tasks[positionTaskCurrent].workflow != null
        ? this.dataDialog.workflow.tasks[positionTaskCurrent].workflow.tasks
        : [];

    sizeWorkflowLevel2 = arrTaskCurrent.length;

    if (arrTaskCurrent.length > 0) {
      for (let index = 0; index < arrTaskCurrent.length; index++) {
        if (arrTaskCurrent[index].status != 'Pending') {
          cont++;
        }
      }
    }

    return (cont / sizeWorkflowLevel2) * 100;
  }
  private calculatedPercentageWorkflow() {
    let cont = 0;
    for (
      let index = 0;
      index < this.dataDialog.workflow.tasks.length;
      index++
    ) {
      if (this.dataDialog.workflow.tasks[index].status == 'Completed') {
        cont++;
      }
    }
    return (cont / this.dataDialog.workflow.tasks.length) * 100;
  }

  /* private generateLetter() {
    let letters = [
      'a',
      'b',
      'c',
      'd',
      'e',
      'f',
      '0',
      '1',
      '2',
      '3',
      '4',
      '5',
      '6',
      '7',
      '8',
      '9',
    ];
    let numRgb: any = (Math.random() * 15).toFixed(0);
    return letters[numRgb];
  }

  private colorHEX() {
    let color = '';
    for (var i = 0; i < 6; i++) {
      color = color + this.generateLetter();
    }
    return '#' + color;
  } */
}
