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

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

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

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

    @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;

    ngOnChanges() {
        this._loadLineChart();
    }

    private _loadLineChart(): void {
        this.chartConfig.lineChartData.labels = [...this.headers];
        this.names.forEach((label: string, index: number) => {
            let fill: string | number | boolean = '-1';
            if (index === 0) {
                fill = true;
            }
            const dataset: ChartDataset<'line'> = {
                data: [...this.values[index]],
                label: label,
                backgroundColor: this.colors.backgroundColor[index],
                borderColor: this.colors.borderColor[index],
                borderWidth: 1,
                fill: fill,
                //stepped: true,
                cubicInterpolationMode: 'monotone',
                tension: 0,
            };
            this.chartConfig.lineChartData.datasets!.push(dataset);
        });
        this.chartConfig.lineChartLegend = this.legend;
        this.displayCharts = true;
    }
}
