import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { ChartistModule, Configuration } from 'ng-chartist';

import { Observable, Subscription } from 'rxjs';

import { MenuItems } from 'src/app/components/shared';
import { UtilitiesService, JumpsService } from 'src/app/core/services';
import { JumpByDate } from 'src/app/core/models';

@Component({
    standalone: true,
    imports: [
        CommonModule,
        MatButtonModule, MatCardModule, MatExpansionModule, MatIconModule, MatMenuModule,
        ChartistModule
    ],
    selector: 'huapp-jumps-by-month',
    templateUrl: './jumps-by-month.component.html'
})
export class JumpsByMonthComponent implements OnInit, OnDestroy {
    private _jumpByDate: Subscription = new Subscription();
    private _jumpsByDate!: Array<JumpByDate>;
    private _jumpsByDateCount = 0;
    public title: string = 'Volume mensuel';
    public subtitle: string = 'Nombre total de sauts par mois';
    public min = 0;
    public max = 0;
    public grandAvg = 0;
    public grandTotal = 0;
    public seriesHeader: string[] = [];
    public seriesName: String[] = [];
    public seriesRow: any[] = [];
    public seriesColor: String[] = this._utilitiesService.getChartColors();
    public seriesRowTotal: number[] = [];
    public seriesRowAvg: number[] = [];
    public seriesColTotal: number[] = [];
    public displayCharts = false;
    public barChartJumps: Configuration = this._utilitiesService.getBarConfig();

    constructor(
        private _jumpsService: JumpsService,
        private _utilitiesService: UtilitiesService,
        public menuItems: MenuItems
    ) { }

    ngOnInit() {
        this._loadJumpByDate();
    }

    ngOnDestroy() {
        this._jumpByDate.unsubscribe();
    }

    private _loadJumpByDate() {
        this.seriesHeader = ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"];
        let values: Array<number> = this.seriesHeader.map(() => 0);
        this.seriesColTotal = [...values];
        const jumps$: Observable<Array<JumpByDate>> = this._jumpsService.getAllByDate();
        this._jumpByDate = jumps$.subscribe((aggregate: Array<JumpByDate>) => {
            this._jumpsByDateCount = aggregate.length;
            this._jumpsByDate = aggregate.map((row: JumpByDate) => {
                let year = row._id.year.toString();
                let month = row._id.month;
                if (this.seriesName.indexOf(year) < 0) {
                    this.seriesName.push(year);
                    if (row._id.year < this.min || this.min == 0) {
                        this.min = row._id.year;
                    }
                    if (row._id.year > this.max) {
                        this.max = row._id.year;
                    }
                    this.seriesRow.push([...values]);
                }
                this.seriesRow[(this.seriesRow.length-1)][(month-1)] = row.count;
                this.seriesColTotal[(month-1)] += row.count;
                return row;
            });
            this.seriesRow.forEach((row: number[]) => {
                const total = row.reduce((partialSum, a) => partialSum + a, 0);
                this.seriesRowTotal.push(total);
            });
            this.seriesRowTotal.forEach((row: number) => {
                let value: number = (row/this.seriesName.length);
                this.seriesRowAvg.push(value);
            });
            this.grandAvg = this.seriesRowAvg.reduce((partialSum, accumulated) => partialSum + accumulated, 0);
            this.grandTotal = this.seriesColTotal.reduce((partialSum, accumulated) => partialSum + accumulated, 0);
            this.barChartJumps = {
                type: 'Bar',
                data: {
                    "labels": this.seriesHeader,
                    "series": this.seriesRow
                },
                options: {
                    seriesBarDistance: 15,
                    high: 70,
                    axisX: {
                        showGrid: false,
                        offset: 20
                    },
                    axisY: {
                        showGrid: true,
                        offset: 40
                    },
                    height: 300
                },
                responsiveOptions: [
                    ['screen and (min-width: 1024px)', {
                        axisX: {
                            labelInterpolationFnc: function(value: number, index: number): string {
                                return index % 1 === 0 ? `${value}` : '';
                            }
                        }
                    }],
                    ['screen and (min-width: 641px) and (max-width: 1024px)', {
                        seriesBarDistance: 10,
                        axisY: {
                            offset: 30
                        },
                        axisX: {
                            labelInterpolationFnc: function(value: any, index: number): string {
                                return index % 1 === 0 ? `${value[0]}` : '';
                            }
                        }
                    }],
                    ['screen and (max-width: 640px)', {
                        seriesBarDistance: 5,
                        axisY: {
                            offset: 20
                        },
                        axisX: {
                            labelInterpolationFnc: function(value: any, index: number): string {
                                return index % 1 === 0 ? `${value[0]}` : '';
                            }
                        }
                    }]
                ]
            };
            this.displayCharts = true;
        });
    }
}
