import * as i0 from '@angular/core';
import { inject, Injectable, Pipe, NgModule } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { user } from '@seniorsistemas/senior-platform-data';
import moment from 'moment';
import { of, from } from 'rxjs';
import { tap, map, switchMap, catchError } from 'rxjs/operators';
import { CookieService } from 'ngx-cookie-service';
import 'moment/locale/es';
import 'moment/locale/pt-br';
import BigNumber from 'bignumber.js';

class CalendarLocaleOptions {
    hourFormat = '24';
    dateFormat = 'dd/mm/yy';
    firstDayOfWeek = 0;
    today = 'Hoje';
    clear = 'Limpar';
    dayNames = ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'];
    dayNamesShort = ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'];
    dayNamesMin = ['D', 'S', 'T', 'Q', 'Q', 'S', 'S'];
    monthNamesShort = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'];
    monthNames = ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'];
    constructor(config = {}) {
        this.clear = config?.clear ?? this.clear;
        this.dateFormat = config?.dateFormat ?? this.dateFormat;
        this.dayNames = config?.dayNames ?? this.dayNames;
        this.dayNamesMin = config?.dayNamesMin ?? this.dayNamesMin;
        this.firstDayOfWeek = config?.firstDayOfWeek ?? this.firstDayOfWeek;
        this.hourFormat = config?.hourFormat ?? this.hourFormat;
        this.monthNames = config?.monthNames ?? this.monthNames;
        this.monthNamesShort = config?.monthNamesShort ?? this.monthNamesShort;
        this.today = config?.today ?? this.today;
    }
}

class NumberLocaleOptions {
    thousandsSeparator = ".";
    decimalSeparator = ",";
    currencySymbol = "R$";
    constructor(config = {}) {
        Object.assign(this, config);
    }
}

class LocaleOptions {
    locale = 'pt-BR';
    calendar = new CalendarLocaleOptions({});
    number = new NumberLocaleOptions();
    constructor(config = {}) {
        this.calendar = config.calendar ?? this.calendar;
        this.number = config.number ?? this.number;
        this.locale = config.locale ?? this.locale;
        // Object.keys(config).forEach(key => (this[key] = config[key] || this[key]));
    }
}

/**
 * @description Serviço de localização que obtém e armazena o locale do usuário
 * a partir da plataforma Senior. Fornece separadores decimais e de milhar,
 * configurações de calendário e opções de formato PrimeNG com base no locale ativo.
 *
 * @category Locale
 */
class LocaleService {
    http = inject(HttpClient);
    cookieService = inject(CookieService);
    locale;
    localeOptions;
    localeOptionsAddress = 'https://cdn.senior.com.br/primeng/locales';
    localeOptionsVersion = '3.0.0';
    VALID_MOMENT_LANGUAGES = {
        spanish: ['es-do', 'es-mx', 'es-us', 'es'],
        english: ['en', 'en-au', 'en-ca', 'en-gb', 'en-ie', 'en-il', 'en-in', 'en-nz', 'en-sg'],
    };
    get() {
        return this.localeOptions
            ? of(this.localeOptions)
            : this.getLocaleConfig().pipe(tap((localeOptions) => (this.localeOptions = { ...localeOptions, locale: this.locale })));
    }
    getLocale() {
        return this.locale
            ? of(this.locale)
            : from(this.getUserData()).pipe(map((userData) => {
                const locale = userData.locale || userData.tenantLocale || 'pt-BR';
                this.locale = locale;
                return this.locale;
            }));
    }
    /**
     * Returns an object with the locale options based on the user's locale(platform locale).
     * @return The locale options object.
     */
    getLocaleOptions() {
        return this.localeOptions;
    }
    getUserData() {
        try {
            return of(JSON.parse(this.cookieService.get('com.senior.token')));
        }
        catch (ex) {
            console.warn('Unable to obtain user locale from cookie, calling getUser');
            return user.getUserData();
        }
    }
    /**
     * Set valid locale for moment js locale based on user current locale.
     * Sometimes the locale from user not exists in locale of moment, for example, is valid user with language 'es-CO' but for the momentjs the locale 'es-CO' not exist, so with this function will be applied the 'es' locale.
     * @param userLocale
     * @returns valid locale based in user locale.
     */
    parseUserLocaleToMoment(userLocale) {
        userLocale = userLocale.toLowerCase();
        if (userLocale.startsWith('es') && !this.VALID_MOMENT_LANGUAGES.spanish.includes(userLocale)) {
            userLocale = 'es';
        }
        if (userLocale.startsWith('en') && !this.VALID_MOMENT_LANGUAGES.english.includes(userLocale)) {
            userLocale = 'en';
        }
        return userLocale;
    }
    getLocaleConfig() {
        return this.getLocale().pipe(switchMap((locale) => {
            moment.locale(this.parseUserLocaleToMoment(locale));
            return this.http
                .get(`${this.localeOptionsAddress}/${this.localeOptionsVersion}/${locale}.json`)
                .pipe(map((response) => new LocaleOptions({ ...response, locale })));
        }), catchError((err) => {
            console.warn(`Error getting locale configuration. Using fallback.`, err);
            return user.getUserData();
        }));
    }
    getGroupingSeparator() {
        const numberFormat = new Intl.NumberFormat(this.locale, {
            style: 'decimal',
            useGrouping: true,
            minimumFractionDigits: 5,
            maximumFractionDigits: 5,
        });
        // The default groupingSeparator for 'fr' is the character code 8239. We need it to be the regular space.
        if (this.locale?.includes('fr'))
            return ' ';
        return numberFormat.formatToParts(1000).find((part) => part.type === 'group')?.value;
    }
    getDecimalSeparator() {
        const numberFormat = new Intl.NumberFormat(this.locale, {
            style: 'decimal',
            minimumFractionDigits: 5,
            maximumFractionDigits: 5,
        });
        return numberFormat.formatToParts(1.2).find((part) => part.type === 'decimal')?.value;
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocaleService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
    static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocaleService });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocaleService, decorators: [{
            type: Injectable
        }] });

function applyLocalizedMask(rawValue, options, isNumber) {
    const { allowNegative, decimalSeparator, scale, prefix, suffix, thousandsSeparator } = options;
    const value = isNumber ? new BigNumber(rawValue).toFixed(scale).toString() : String(rawValue);
    const onlyNumbers = value.replace(/\D/g, '');
    if (!onlyNumbers) {
        return '';
    }
    const integerPart = onlyNumbers
        .slice(0, onlyNumbers.length - scale)
        .replace(/^0*/g, '')
        .replace(/\B(?=(\d{3})+(?!\d))/g, thousandsSeparator) || '0';
    const decimalPart = onlyNumbers.slice(onlyNumbers.length - scale);
    const newValue = scale ? integerPart + decimalSeparator + decimalPart : integerPart;
    const isZero = !integerPart && !decimalPart;
    const operator = String(value).includes('-') && allowNegative && !isZero ? '-' : '';
    return `${operator}${prefix}${newValue}${suffix}`;
}

class LocalizedBignumberPipe {
    localeService = inject(LocaleService);
    transform(value, options) {
        return value !== undefined && value !== null ? this.applyMask(value, options) : of(value);
    }
    applyMask(value, options) {
        return this.localeService.get().pipe(map((localeConfig) => {
            const configs = {
                prefix: options?.prefix ?? localeConfig?.number?.currencySymbol ?? 'R$',
                thousandsSeparator: options?.thousandsSeparator ?? localeConfig?.number?.thousandsSeparator ?? '.',
                decimalSeparator: options?.decimalSeparator ?? localeConfig?.number?.decimalSeparator ?? ',',
                scale: options?.scale ?? 2,
                suffix: options?.suffix ?? '',
                allowNegative: options?.allowNegative ?? true,
            };
            const isNumber = !new BigNumber(value).isNaN();
            return applyLocalizedMask(value, configs, isNumber);
        }));
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocalizedBignumberPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
    static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "18.2.14", ngImport: i0, type: LocalizedBignumberPipe, isStandalone: true, name: "localizedBignumber" });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocalizedBignumberPipe, decorators: [{
            type: Pipe,
            args: [{
                    name: 'localizedBignumber',
                    standalone: true,
                }]
        }] });

class LocalizedBignumberImpurePipe extends LocalizedBignumberPipe {
    transform(value, options) {
        return super.transform(value, options);
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocalizedBignumberImpurePipe, deps: null, target: i0.ɵɵFactoryTarget.Pipe });
    static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "18.2.14", ngImport: i0, type: LocalizedBignumberImpurePipe, isStandalone: true, name: "localizedBignumberImpure", pure: false });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocalizedBignumberImpurePipe, decorators: [{
            type: Pipe,
            args: [{
                    name: 'localizedBignumberImpure',
                    pure: false,
                    standalone: true,
                }]
        }] });

class LocalizedCurrencyPipeOptions extends NumberLocaleOptions {
    scale = 2;
    constructor(config = {}) {
        super(config);
    }
}
/**
 * @deprecated Should use localizedBignumberPipe instead
 */
class LocalizedCurrencyPipe {
    localeService = inject(LocaleService);
    transform(value, options) {
        if (!options) {
            options = new LocalizedCurrencyPipeOptions();
        }
        return value !== undefined && value !== null ? this.applyMask(value, options) : of(value);
    }
    applyMask(value, options) {
        return this.localeService.get().pipe(map((localeConfig) => {
            const config = { ...localeConfig.number, ...options };
            const { scale, currencySymbol, thousandsSeparator, decimalSeparator } = config;
            const rawValue = Number(value).toFixed(scale);
            const onlyNumbers = rawValue.replace(/[^0-9]/g, ``);
            const integerPart = onlyNumbers
                .slice(0, onlyNumbers.length - scale)
                .replace(/^0*/g, ``)
                .replace(/\B(?=(\d{3})+(?!\d))/g, thousandsSeparator) || `0`;
            const decimalPart = onlyNumbers.slice(onlyNumbers.length - scale);
            const newValue = scale ? integerPart + decimalSeparator + decimalPart : integerPart;
            const isZero = !Number(onlyNumbers);
            const operator = rawValue.includes('-') && !isZero ? '-' : '';
            return `${operator}${currencySymbol}${newValue}`;
        }));
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocalizedCurrencyPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
    static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "18.2.14", ngImport: i0, type: LocalizedCurrencyPipe, isStandalone: true, name: "localizedCurrency" });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocalizedCurrencyPipe, decorators: [{
            type: Pipe,
            args: [{
                    name: 'localizedCurrency',
                    standalone: true,
                }]
        }] });

/**
 * @deprecated Should use localizedBignumberPipe instead
 */
class LocalizedCurrencyImpurePipe extends LocalizedCurrencyPipe {
    transform(value, options = new LocalizedCurrencyPipeOptions()) {
        return super.transform(value, options);
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocalizedCurrencyImpurePipe, deps: null, target: i0.ɵɵFactoryTarget.Pipe });
    static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "18.2.14", ngImport: i0, type: LocalizedCurrencyImpurePipe, isStandalone: true, name: "localizedCurrencyImpure", pure: false });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocalizedCurrencyImpurePipe, decorators: [{
            type: Pipe,
            args: [{
                    name: 'localizedCurrencyImpure',
                    pure: false,
                    standalone: true,
                }]
        }] });

class LocalizedDatePipe {
    localeService = inject(LocaleService);
    transform(value, format = 'L LTS') {
        return this.localeService.get().pipe(map(() => (value ? moment(value).format(format) : value)));
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocalizedDatePipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
    static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "18.2.14", ngImport: i0, type: LocalizedDatePipe, isStandalone: true, name: "localizedDate" });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocalizedDatePipe, decorators: [{
            type: Pipe,
            args: [{
                    name: 'localizedDate',
                    standalone: true,
                }]
        }] });

class LocalizedDateImpurePipe extends LocalizedDatePipe {
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocalizedDateImpurePipe, deps: null, target: i0.ɵɵFactoryTarget.Pipe });
    static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "18.2.14", ngImport: i0, type: LocalizedDateImpurePipe, isStandalone: true, name: "localizedDateImpure", pure: false });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocalizedDateImpurePipe, decorators: [{
            type: Pipe,
            args: [{
                    name: 'localizedDateImpure',
                    pure: false,
                    standalone: true,
                }]
        }] });

/**
 * @deprecated Should use localizedBignumberPipe instead
 */
class LocalizedNumberPipe {
    localeService = inject(LocaleService);
    transform(value, minimumFractionDigits) {
        return from(this.localeService.getLocale()).pipe(map((locale) => {
            const numericValue = Number(value);
            if (!value && isNaN(numericValue))
                return;
            return new Intl.NumberFormat(locale, {
                minimumFractionDigits: minimumFractionDigits || 0,
            }).format(Number(value));
        }));
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocalizedNumberPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
    static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "18.2.14", ngImport: i0, type: LocalizedNumberPipe, isStandalone: true, name: "localizedNumber" });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocalizedNumberPipe, decorators: [{
            type: Pipe,
            args: [{
                    name: 'localizedNumber',
                    standalone: true,
                }]
        }] });

class LocalizedTimePipe {
    localeService = inject(LocaleService);
    transform(value, format = 'LTS') {
        return this.localeService.get().pipe(map(() => (value ? moment(value, 'HH:mm:ss').format(format) : value)));
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocalizedTimePipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
    static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "18.2.14", ngImport: i0, type: LocalizedTimePipe, isStandalone: true, name: "localizedTime" });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocalizedTimePipe, decorators: [{
            type: Pipe,
            args: [{
                    name: 'localizedTime',
                    standalone: true,
                }]
        }] });

class LocalizedTimeImpurePipe extends LocalizedTimePipe {
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocalizedTimeImpurePipe, deps: null, target: i0.ɵɵFactoryTarget.Pipe });
    static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "18.2.14", ngImport: i0, type: LocalizedTimeImpurePipe, isStandalone: true, name: "localizedTimeImpure", pure: false });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocalizedTimeImpurePipe, decorators: [{
            type: Pipe,
            args: [{
                    name: 'localizedTimeImpure',
                    pure: false,
                    standalone: true,
                }]
        }] });

class LocaleModule {
    static forRoot() {
        return {
            ngModule: LocaleModule,
            providers: [
                LocaleService,
                LocalizedCurrencyPipe,
                LocalizedDatePipe,
                LocalizedTimePipe,
                LocalizedNumberPipe,
                LocalizedCurrencyImpurePipe,
                LocalizedDateImpurePipe,
                LocalizedTimeImpurePipe,
                LocalizedBignumberPipe,
                LocalizedBignumberImpurePipe,
            ],
        };
    }
    static forChild() {
        return {
            ngModule: LocaleModule,
        };
    }
    static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocaleModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
    static ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "18.2.14", ngImport: i0, type: LocaleModule, imports: [LocalizedCurrencyPipe,
            LocalizedDatePipe,
            LocalizedTimePipe,
            LocalizedNumberPipe,
            LocalizedCurrencyImpurePipe,
            LocalizedDateImpurePipe,
            LocalizedTimeImpurePipe,
            LocalizedBignumberPipe,
            LocalizedBignumberImpurePipe], exports: [LocalizedCurrencyPipe,
            LocalizedDatePipe,
            LocalizedTimePipe,
            LocalizedNumberPipe,
            LocalizedCurrencyImpurePipe,
            LocalizedDateImpurePipe,
            LocalizedTimeImpurePipe,
            LocalizedBignumberPipe,
            LocalizedBignumberImpurePipe] });
    static ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocaleModule });
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "18.2.14", ngImport: i0, type: LocaleModule, decorators: [{
            type: NgModule,
            args: [{
                    imports: [
                        LocalizedCurrencyPipe,
                        LocalizedDatePipe,
                        LocalizedTimePipe,
                        LocalizedNumberPipe,
                        LocalizedCurrencyImpurePipe,
                        LocalizedDateImpurePipe,
                        LocalizedTimeImpurePipe,
                        LocalizedBignumberPipe,
                        LocalizedBignumberImpurePipe,
                    ],
                    exports: [
                        LocalizedCurrencyPipe,
                        LocalizedDatePipe,
                        LocalizedTimePipe,
                        LocalizedNumberPipe,
                        LocalizedCurrencyImpurePipe,
                        LocalizedDateImpurePipe,
                        LocalizedTimeImpurePipe,
                        LocalizedBignumberPipe,
                        LocalizedBignumberImpurePipe,
                    ],
                }]
        }] });

/**
 * Generated bundle index. Do not edit.
 */

export { CalendarLocaleOptions, LocaleModule, LocaleOptions, LocaleService, LocalizedBignumberImpurePipe, LocalizedBignumberPipe, LocalizedCurrencyImpurePipe, LocalizedCurrencyPipe, LocalizedCurrencyPipeOptions, LocalizedDateImpurePipe, LocalizedDatePipe, LocalizedNumberPipe, LocalizedTimeImpurePipe, LocalizedTimePipe, NumberLocaleOptions, applyLocalizedMask };
//# sourceMappingURL=seniorsistemas-angular-components-locale.mjs.map
