import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { LicenseService } from '@services/license.service';
import { map } from 'rxjs/operators';
import type { ILicenseReport } from '@red/domain';
import { ChartDataset } from 'chart.js';
import { ChartBlue, ChartGreen, ChartRed } from '../../utils/constants';
import { getLabelsFromLicense, getLineConfig } from '../../utils/functions';

@Component({
    selector: 'red-license-usage',
    templateUrl: './license-usage.component.html',
    styleUrls: ['./license-usage.component.scss'],
})
export class LicenseUsageComponent {
    readonly analysisPercentageOfLicense$ = this.licenseService.selectedLicense$.pipe(map(() => this.getAnalysisPercentageOfLicense()));
    readonly data$ = this.licenseService.selectedLicense$.pipe(
        map(() => this.licenseService.currentLicenseReport),
        map(license => ({
            datasets: this.#getDatasets(license),
            labels: getLabelsFromLicense(license),
        })),
    );

    constructor(readonly licenseService: LicenseService, private readonly _translateService: TranslateService) {}

    getAnalysisPercentageOfLicense() {
        const totalLicensedNumberOfPages = this.licenseService.totalLicensedNumberOfPages;
        const numberOfAnalyzedPages = this.licenseService.analyzedPagesInCurrentLicensingPeriod;
        return totalLicensedNumberOfPages > 0 ? (numberOfAnalyzedPages / totalLicensedNumberOfPages) * 100 : 100;
    }

    #getDatasets(license: ILicenseReport): ChartDataset[] {
        const monthlyData = license.monthlyData;

        return [
            {
                data: monthlyData.flatMap(d => d.numberOfAnalyzedPages),
                label: 'Pages per Month',
                type: 'bar',
                backgroundColor: ChartBlue,
                borderColor: ChartBlue,
                order: 2,
            },
            {
                data: monthlyData.flatMap(() => 200000),
                label: 'Total Pages',
                ...getLineConfig(ChartRed, false),
                yAxisID: 'y1',
                order: 1,
            },
            {
                data: monthlyData.map(
                    (month, monthIndex) =>
                        month.numberOfAnalyzedPages +
                        monthlyData.slice(0, monthIndex).reduce((acc, curr) => acc + curr.numberOfAnalyzedPages, 0),
                ),
                label: 'Cumulative Pages',
                yAxisID: 'y1',
                order: 1,
                ...getLineConfig(ChartGreen, false),
            },
        ];
    }
}
