import { Injectable } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { first } from 'rxjs/operators';

type IMonthNames = {
    [key: number]: string;
};

@Injectable({
    providedIn: 'root',
})
export class DatesTranslationService {
    private monthsNames: IMonthNames = {};
    private monthsFullNames: IMonthNames = {};
    initialized = false;

    constructor(private translateService: TranslateService) {}

    private getTranslations() {
        return this.translateService
            .get([
                'MONTH-SHORT.1',
                'MONTH-SHORT.2',
                'MONTH-SHORT.3',
                'MONTH-SHORT.4',
                'MONTH-SHORT.5',
                'MONTH-SHORT.6',
                'MONTH-SHORT.7',
                'MONTH-SHORT.8',
                'MONTH-SHORT.9',
                'MONTH-SHORT.10',
                'MONTH-SHORT.11',
                'MONTH-SHORT.12',
                'OF-MONTH.1',
                'OF-MONTH.2',
                'OF-MONTH.3',
                'OF-MONTH.4',
                'OF-MONTH.5',
                'OF-MONTH.6',
                'OF-MONTH.7',
                'OF-MONTH.8',
                'OF-MONTH.9',
                'OF-MONTH.10',
                'OF-MONTH.11',
                'OF-MONTH.12',
            ])
            .pipe(first())
            .toPromise();
    }

    async init() {
        if (this.initialized) {
            return Promise.resolve(true);
        }

        const values = await this.getTranslations();

        for (let i = 0; i < 12; i++) {
            const shortNameKey = `MONTH-SHORT.${i + 1}`;
            const fullNameKey = `OF-MONTH.${i + 1}`;

            this.monthsNames[i] = values[shortNameKey];
            this.monthsFullNames[i] = values[fullNameKey];
        }

        this.initialized = true;

        return Promise.resolve(true);
    }

    public getMonthName(monthNumber: number) {
        return this.monthsNames[monthNumber];
    }

    public getMonthFullName(monthNumber: number) {
        return this.monthsFullNames[monthNumber];
    }

    public getShortDateString(date: Date) {
        return `${date.getDate()} ${this.getMonthName(date.getMonth())}`;
    }

    public getFullDateString(date: Date, withYear = false) {
        const paddedDate = `0${date.getDate()}`.slice(-2);
        const monthName = this.getMonthFullName(date.getMonth());

        return withYear
            ? `${paddedDate} ${monthName} ${date.getFullYear()}`
            : `${paddedDate} ${monthName}`;
    }
}
