import { Component, Input, OnChanges, inject } from '@angular/core';
import { ChartDataset, Point } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';

import { UtilitiesService } from '@services';
import { LineConfig } from '@models';

@Component({
    selector: 'app-line-chart',
    imports: [BaseChartDirective],
    templateUrl: './line-chart.component.html',
})
export class LineChartComponent implements OnChanges {
    private _utilitiesService = inject(UtilitiesService);

    public displayCharts = false;
    public chartConfig: LineConfig = this._utilitiesService.getLineChartConfig();

    @Input() headers: string[] = [];
    @Input() names: string[] = [];
    @Input() values: Array<Array<number>> = [];
    @Input() colors: {
        backgroundColor: string[];
        borderColor: string[];
    } = {
        backgroundColor: this._utilitiesService.getSeriesColors(0.8),
        borderColor: this._utilitiesService.getSeriesColors(1),
    };
    @Input() legend: boolean = false;
    @Input() hideZero: boolean = false;

    ngOnChanges() {
        this._loadLineChart();
    }

    private _loadLineChart(): void {
        this.chartConfig.lineChartData.labels = [...this.headers];
        this.names.forEach((label: string, index: number) => {
            let data: Array<number | Point | null> = [];
            if (this.hideZero) {
                data = [...this.values[index].map((value) => (value === 0 ? null : value))];
            } else {
                data = [...this.values[index]];
            }
            const dataset: ChartDataset<'line'> = {
                data: data,
                label: label,
                backgroundColor: this.colors.backgroundColor[index],
                borderColor: this.colors.borderColor[index],
                borderWidth: 2,
                cubicInterpolationMode: 'monotone',
                tension: 0,
            };
            this.chartConfig.lineChartData.datasets!.push(dataset);
        });
        this.chartConfig.lineChartLegend = this.legend;
        this.displayCharts = true;
    }
}
