import { Component, Input } from '@angular/core';
import { EnrollNumberAllUsageOutput } from '~/pages/sts/entities/output/enrollNumberAllUsageOutput';

@Component({
    selector: 'StsDetailStatsData',
    moduleId: module.id,
    templateUrl: './sts-detail-stats-data.component.html',
    styleUrls: ['./_sts-detail-stats-data.component.scss']
})
export class StsDetailStatsDataComponent {
    statDataByDate: any;
    statDataByDateKeys: string[];
    typeToDisplayName = {
        data: 'Datové přenosy',
        sms: 'SMS v síti T-Mobile',
        smsout: 'SMS mimo síť T-Mobile',
        call: 'Volání v síti T-Mobile',
        callsts: 'Volání v STS (zdarma)',
        callout: 'Volání mimo síť T-Mobile'
    };

    /**
     * It prepare data for table of usages.
     * It create object where key is date, and value is object with data
     *
     * @param {EnrollNumberAllUsageOutput[]} value
     */
    @Input() set enrollNumberUsages(value: EnrollNumberAllUsageOutput[]) {
        this.statDataByDate = value.reduce((acc: any, curr) => {
            if (curr.Month && curr.Year && curr.ID_CallServiceType && Object.keys(this.typeToDisplayName).indexOf(curr.ID_CallServiceType) !== -1) {
                if (acc.hasOwnProperty(`${curr.Month}. ${curr.Year}`)) {
                    const indexOfType = acc[`${curr.Month}. ${curr.Year}`].findIndex(e => e.type === curr.ID_CallServiceType);
                    if (indexOfType !== -1) { // if under date is something with same type like curr -> update
                        acc[`${curr.Month}. ${curr.Year}`][indexOfType] = {
                            ...acc[`${curr.Month}. ${curr.Year}`][indexOfType],
                            additionallyFee: !curr.IsMonthlyFee ? curr.Quantity : acc[`${curr.Month}. ${curr.Year}`][indexOfType].additionallyFee
                        };
                    } else { // if under date is something but different type
                        acc[`${curr.Month}. ${curr.Year}`].push({
                            type: curr.ID_CallServiceType,
                            label: curr.DisplayName,
                            additionallyFee: !curr.IsMonthlyFee ? curr.Quantity : 0,
                            unit: curr.Unit
                        });
                    }
                } else {
                    acc[`${curr.Month}. ${curr.Year}`] = [{ // if under date is not anything
                        type: curr.ID_CallServiceType,
                        label: curr.DisplayName,
                        additionallyFee: !curr.IsMonthlyFee ? curr.Quantity : 0,
                        unit: curr.Unit
                    }];
                }
            }

            return acc;
        }, {});

        this.statDataByDateKeys = Object.keys(this.statDataByDate);
    }
}
