import { Component } from '@angular/core';
import { LicenseService } from '@services/license.service';
import { map } from 'rxjs/operators';
import { ChartDataset } from 'chart.js';
import { ChartBlue, ChartGreen, ChartRed } from '../../utils/constants';
import { getLabelsFromLicense, getLineConfig } from '../../utils/functions';
import { TranslateService } from '@ngx-translate/core';
import { marker as _ } from '@biesbjerg/ngx-translate-extract-marker';

@Component({
    selector: 'red-license-page-usage',
    templateUrl: './license-page-usage.component.html',
    styleUrls: ['./license-page-usage.component.scss'],
})
export class LicensePageUsageComponent {
    readonly data$ = this.licenseService.selectedLicense$.pipe(map(() => this.#getData()));

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

    #getData() {
        const yAxisLabel = _('license-info-screen.page-usage.pages-per-month');
        const yAxisLabelRight = _('license-info-screen.page-usage.total-pages');

        return {
            datasets: this.#getPagesDatasets(),
            labels: getLabelsFromLicense(this.licenseService.selectedLicenseReport),
            yAxisLabel: this._translateService.instant(yAxisLabel),
            yAxisLabelRight: this._translateService.instant(yAxisLabelRight),
        };
    }

    #getPagesDatasets(): ChartDataset[] {
        const monthlyData = this.licenseService.selectedLicenseReport.monthlyData;

        return [
            {
                data: monthlyData.flatMap(d => d.numberOfAnalyzedPages),
                label: this._translateService.instant('license-info-screen.page-usage.pages-per-month'),
                type: 'bar',
                backgroundColor: ChartBlue,
                borderColor: ChartBlue,
                order: 2,
            },
            {
                data: monthlyData.flatMap(() => this.licenseService.totalLicensedNumberOfPages),
                label: this._translateService.instant('license-info-screen.page-usage.total-pages'),
                ...getLineConfig(ChartRed, true, false),
                yAxisID: 'y1',
                order: 1,
            },
            {
                data: monthlyData.map(
                    (month, monthIndex) =>
                        month.numberOfAnalyzedPages +
                        monthlyData.slice(0, monthIndex).reduce((acc, curr) => acc + curr.numberOfAnalyzedPages, 0),
                ),
                label: this._translateService.instant('license-info-screen.page-usage.cumulative-pages'),
                yAxisID: 'y1',
                order: 1,
                ...getLineConfig(ChartGreen, true, false),
            },
        ];
    }
}
