import * as d3 from 'd3';
import { ChartConfiguration } from "../chart-base/chart-configuration";
import { PieChart } from "../charts/pie-chart";

export class PieChartHelper {
    private container: any;
    private containerId: string = 'pie-chart-container';
    private svgId: string = 'pie-chart';

    private selector: any;

    private config: ChartConfiguration = new ChartConfiguration(`#${this.svgId}`, { width: 400, height: 408 });
    private chart: PieChart;

    private data: any[] = [];

    public setData(data: any) {
        this.data = data;
    }

    public appendChart() {
        // Add div container
        this.container = d3.select('#medalDistributionByGenderChart')
            .append('div')
            .attr('class', 'container')
            .attr('style', 'width: fit-content;')
            .attr('id', `${this.containerId}`);

        // Add year selector
        this.selector = this.container.append('div')
            .attr('id', 'pie-chart-selector')
            .attr('class', 'text-center mt-4');

        this.selector.append('label')
            .attr('for', 'yearSelector')
            .attr('class', 'form-label')
            .style('font-weight', 'bold')
            .text('Select year:');
        this.selector.append('select')
            .attr('class', 'form-select text-center')
            .append('option').attr('value', 'all').text('All years');
        const selectField = this.selector.select('select');
        const years = Array.from(new Set(this.data.map(d => d.Year))); // Get unique years
        years.forEach(year => {
            selectField.append("option")
                .attr("value", year)
                .text(year);
        });
        // add select event handler
        const visHelper = this;
        selectField.on("change", function (event: any) {
            const selectedYear = d3.select(event.target).property("value");
            visHelper.updateChart(selectedYear);
        });

        // add svg for chart
        this.container
            .append('svg')
            .attr('id', `${this.svgId}`);

        // init chart
        this.chart = new PieChart(this.config);
        this.updateChart("all");

    }

    private updateChart(selectedYear: string) {
        this.chart.data = this.processData(selectedYear);
        this.chart.updateVis();
    }

    private processData(selectedYear: string) {
        const filteredData = selectedYear !== 'all' ? this.data.filter(d => d.Year === selectedYear) : this.data;

        const genderCountMap: { [key: string]: number } = {};
        filteredData.forEach(d => {
            const gender = d.Gender;
            if (genderCountMap[gender]) {
                genderCountMap[gender]++;
            } else {
                genderCountMap[gender] = 1;
            }
        });
        const result: any[] = Object.keys(genderCountMap).map(key => ({
            key: key,
            value: genderCountMap[key]
        }));

        return result;
    }
}

