import React from "react";
import ReactApexChart from "react-apexcharts";
import { ApiQueryFilters } from "../data-contracts/ApiQueryFilter";
import { DataService } from "../services/DataService";
import { ChartComponentProps } from "../types/ChartComponentProps";
import { ChartComponentState } from "../types/ChartComponentState";





class BarChartComponent extends React.Component<
  ChartComponentProps,
  ChartComponentState
> {

  data: any[] = [];
  constructor(props) {
    super(props);
    const filters = new ApiQueryFilters();
    const dataService = new DataService();
    dataService.getDataByFilters(filters,this.props.widget.EntityName||'')
    .then((response:any)=>{
      console.log("dataService.getDataByFilters",response);
      this.data = response.data.Result;
      this.InitChart();
    })

    
    this.state = {
      series: [
        {
          data: [],
        },
      ],
      options: {
        chart: {
          type: "bar",
          height: 350,
          events: {
            dataPointSelection: function (event, chartContext, config)
            {
              const data = config.w.config.xaxis.categories[config.seriesIndex];
              console.log("Selected " + data);
            },
          },
        },
        colors: ["#22D792", "#2C99F7", "#FBC445", "#F74E49", "#717585"],
        plotOptions: {
          bar: {
            borderRadius: 4,
            horizontal: true,
          },
        },
        dataLabels: {
          enabled: false,
        },
        xaxis: {
          categories: [],
        },
      },
    };

  }


  private InitChart()
  {
    const groups = this.GroupItems();


    const catItems = Object.keys(groups);
    const dataItems: any[] = Object.values(groups);


    this.setState( {
      series: [
        {
          data: dataItems,
        },
      ],
      options: {
        chart: {
          type: "bar",
          height: 350,
          events: {
            dataPointSelection: function (event, chartContext, config)
            {
              const data = config.w.config.xaxis.categories[config.seriesIndex];
              console.log("Selected " + data);
            },
          },
        },
        colors: ["#22D792", "#2C99F7", "#FBC445", "#F74E49", "#717585"],
        plotOptions: {
          bar: {
            borderRadius: 4,
            horizontal: true,
          },
        },
        dataLabels: {
          enabled: false,
        },
        xaxis: {
          categories: catItems,
        },
      },
    });
  }
  // private GroupItems()
  // {
  //   return this.data.reduce((groups, record) =>
  //   {
  //     const fieldName = this.props.widget.ValueFieldName + '';

  //     const group = (groups[record] || []);
  //     group.push(record);

  //     const recordCategory = record[this.props.widget.ValueFieldName + ''];
  //     groups[record[fieldName]] = groups[recordCategory] + 1 || 0;
  //     return groups;
  //   }, {});
  // }
  private GroupItems()
  {
    let groups = this.data.reduce((groups, record) =>
    {
      const CreateGroup = (groups: any, record: any) =>
      {
        const group = (groups[record] || []);
        group.push(record);
      }
      const SetGroupData = () => {
        const groupByFieldName = this.props.widget.Group + "";
        const valueFieldName = this.props.widget.ValueFieldName + "";
        const recordCategory = record[groupByFieldName];
        const recordValue = record[valueFieldName];
        let currentGroupValue = groups[record[groupByFieldName]];
        
        switch (this.props.widget.CalcType) {
          case "Count": {
            if (!currentGroupValue) currentGroupValue = 0;
            currentGroupValue = currentGroupValue + 1;
            break;
          }
          case "Sum": {
            if (!currentGroupValue) currentGroupValue = 0;
            currentGroupValue = currentGroupValue + recordValue;
            break;
          }
          case "Max": {
            if (!currentGroupValue) currentGroupValue = -9999999999999;

            if (recordValue > currentGroupValue)
              currentGroupValue = recordValue;
            break;
          }
          case "Min": {
            if (!currentGroupValue) currentGroupValue = 9999999999999;

            if (recordValue < currentGroupValue)
              currentGroupValue = recordValue;
            break;
          }
          case "Average": {
            if (!currentGroupValue) currentGroupValue = [];
            currentGroupValue.push(recordValue);
            break;
          }
        }

        groups[record[groupByFieldName]] = currentGroupValue;
      };

      CreateGroup(groups, record);
      SetGroupData();
      return groups;      
    }, {});

    if(this.props.widget.CalcType == "Average"){
      for (const key in groups) {
        if (Object.prototype.hasOwnProperty.call(groups, key)) {
          const groupArray: any[] = groups[key];
          let sum = groupArray.reduce((a, b) => a + (b[key] || 0), 0);
          let avg = sum / groupArray.length;
          groups[key] = avg;
        }
      }
    }
    return groups;
  }

  render() {
    return (

      <div id="chart">
        <div>
          {this.props.dateFilter && <div className="filter-label">  Date: {this.props.dateFilter.toLocaleDateString("en-US")+''}</div>}
        </div>
        {/* <div>
           {this.props.widget?.EntityName}: {this.props.widget?.CalcType} of {this.props.widget?.ValueFieldName} 
        </div> */}
        <ReactApexChart
          options={this.state.options}
          series={this.state.series}
          type="bar"
          height={"100%"}
        />
      </div>
    );
  }
}

export default BarChartComponent;
