import { Component, Input } from '@angular/core';
import { StatsDataBase } from '~/pages/sts/entities/stats-data-base';

@Component({
    selector: 'StsStatsData',
    moduleId: module.id,
    templateUrl: './sts-stats-data.component.html',
    styleUrls: ['./_sts-stats-data.component.scss']
})
export class StsStatsDataComponent {
    statsDataByDate: any;
    statsDataByDateKeys: string[];

    /**
     * It create object where key is date and value is StatsDataBase entity
     * To the keys property are store sorted keys (ASC)
     *
     * @param {StatsDataBase[]} value
     */
    @Input() set statsDataBase(value: StatsDataBase[]) {
        this.statsDataByDate = value.reduce((acc: any, curr) => {
            if (curr.date) {
                if (acc.hasOwnProperty(curr.date)) {
                    acc[curr.date].push(curr);
                } else {
                    acc[curr.date] = [curr];
                }
            }

            return acc;
        }, {});

        this.statsDataByDateKeys = Object.keys(this.statsDataByDate)
            .sort((a, b) => {
                const [aDay, aYear] = a.split('.');
                const [bDay, bYear] = b.split('.');

                if (parseInt(aYear, 10) === parseInt(bYear, 10)) {
                    if (parseInt(aDay, 10) < parseInt(bDay, 10)) {
                        return 1;
                    } else {
                        return -1;
                    }
                } else if (parseInt(aYear, 10) < parseInt(bYear, 10)) {
                    return 1;
                } else {
                    return -1;
                }
            });
    }
}
