import { Directive, Pipe, NgModule, EventEmitter, Injectable } from '@angular/core';
import { NG_VALIDATORS } from '@angular/forms';
import { CommonModule } from '@angular/common';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { forkJoin } from 'rxjs';
import { map } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

class DateValidator {
    constructor() {
        this.validator = this.dateValidator();
    }
    validate(c) {
        return this.validator(c);
    }
    dateValidator() {
        return (control) => {
            const date = control.value;
            if (date === null || date === undefined) {
                return { 'dateValidator': false };
            }
            control.markAsTouched();
            const toDay = new Date();
            if (typeof date._i === 'object') {
                if (!(date._i.date > 0 && date._i.date <= 31)
                    || !((date._i.month + 1) > 0 && (date._i.month + 1) <= 12)
                    || !(date._i.year > (toDay.getFullYear() - 120))) {
                    return { 'dateValidator': true };
                }
            }
            else if (typeof date._i === 'string') {
                const buffer = date._i.split('/');
                if (buffer.length === 1 && date._i.length === 8) {
                    buffer[0] = date._i.substr(0, 2);
                    buffer[1] = date._i.substr(2, 2);
                    buffer[2] = date._i.substr(4, 4);
                }
                if (buffer.length < 3
                    || !(Number(buffer[0]) > 0 && Number(buffer[0]) <= 31)
                    || !(Number(buffer[1]) > 0 && Number(buffer[1]) <= 12)
                    || !(Number(buffer[2]) > (toDay.getFullYear() - 120) && Number(buffer[2]))) {
                    return { 'dateValidator': true };
                }
            }
            else {
                const newdate = new Date(date);
                const day = newdate.getDate();
                const month = newdate.getMonth();
                const year = newdate.getFullYear();
                if (!(day > 0 && day <= 31)
                    || !((month + 1) > 0 && (month + 1) <= 12)
                    || !(year && year > (toDay.getFullYear() - 120))) {
                    return { 'dateValidator': true };
                }
            }
            return null;
        };
    }
}
DateValidator.decorators = [
    { type: Directive, args: [{
                selector: '[dateValidator][ngModel]',
                providers: [
                    {
                        provide: NG_VALIDATORS,
                        useExisting: DateValidator,
                        multi: true
                    }
                ]
            },] }
];
DateValidator.ctorParameters = () => [];

class CpfValidator {
    constructor() {
        this.validator = this.cpfValidator();
    }
    validate(c) {
        return this.validator(c);
    }
    cpfValidator() {
        return (control) => {
            let cpf = control.value;
            if (cpf === null || cpf === undefined) {
                return { 'cpfValidator': false };
            }
            const regExp = RegExp('[0-9]{3}\.?[0-9]{3}\.?[0-9]{3}\-?[0-9]{2}');
            control.markAsTouched();
            if (!regExp.test(cpf)) {
                return { 'cpfValidator': false };
            }
            cpf = cpf.replace(/\./g, '');
            cpf = cpf.replace(/\-/g, '');
            cpf = cpf.replace(/\_/g, '');
            if (cpf.length !== 11) {
                return { 'cpfValidator': false };
            }
            const c = cpf.substr(0, 9);
            const dv = cpf.substr(9, 2);
            let d1 = 0;
            for (let i = 0; i < 9; i++) {
                d1 += c.charAt(i) * (10 - i);
            }
            if (d1 === 0) {
                return { 'cpfValidator': false };
            }
            d1 = 11 - (d1 % 11);
            if (d1 > 9) {
                d1 = 0;
            }
            if (Number(dv.charAt(0)) !== d1) {
                return { 'cpfValidator': false };
            }
            d1 *= 2;
            for (let i = 0; i < 9; i++) {
                d1 += c.charAt(i) * (11 - i);
            }
            d1 = 11 - (d1 % 11);
            if (d1 > 9) {
                d1 = 0;
            }
            if (Number(dv.charAt(1)) !== d1) {
                return { 'cpfValidator': false };
            }
            return null;
        };
    }
}
CpfValidator.decorators = [
    { type: Directive, args: [{
                selector: '[cpfValidator][ngModel]',
                providers: [
                    {
                        provide: NG_VALIDATORS,
                        useExisting: CpfValidator,
                        multi: true
                    }
                ]
            },] }
];
CpfValidator.ctorParameters = () => [];

class EmailValidator {
    constructor() {
        this.validator = this.emailValidator();
    }
    validate(c) {
        return this.validator(c);
    }
    emailValidator() {
        return (control) => {
            const email = control.value;
            const regExp = RegExp('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$');
            control.markAsTouched();
            if (email !== null && email !== undefined && !regExp.test(email)) {
                return { 'emailValidator': true };
            }
            return null;
        };
    }
}
EmailValidator.decorators = [
    { type: Directive, args: [{
                selector: '[emailValidator][ngModel]',
                providers: [
                    {
                        provide: NG_VALIDATORS,
                        useExisting: EmailValidator,
                        multi: true
                    }
                ]
            },] }
];
EmailValidator.ctorParameters = () => [];

class NameValidator {
    constructor() {
        this.validator = this.nameValidator();
    }
    validate(c) {
        return this.validator(c);
    }
    nameValidator() {
        return (control) => {
            const text = control.value;
            if (text === null || text === undefined) {
                return { 'nameValidator': false };
            }
            control.markAsTouched();
            const regExp = RegExp('^([A-Za-zà-úÀ-Ú]|[0-9]| )+$');
            if (!regExp.test(text)) {
                return { 'nameValidator': false };
            }
            const parts = text.split(' ');
            const current = (parts.length - 1);
            if (current < 1) {
                return { 'nameValidator': false };
            }
            return null;
        };
    }
}
NameValidator.decorators = [
    { type: Directive, args: [{
                selector: '[nameValidator][ngModel]',
                providers: [
                    {
                        provide: NG_VALIDATORS,
                        useExisting: NameValidator,
                        multi: true
                    }
                ]
            },] }
];
NameValidator.ctorParameters = () => [];

class ResumeNames {
    transform(value) {
        if (value) {
            const args = value.trim().split(' ');
            if (args.length > 1) {
                return args[0] + ' ' + args[args.length - 1];
            }
            return args[1];
        }
        return null;
    }
}
ResumeNames.decorators = [
    { type: Pipe, args: [{ name: 'resumeNames' },] }
];

class FirstLetterSplit {
    transform(value) {
        if (value) {
            const args = value.trim().split(' ');
            let newValue = [];
            args.forEach(element => {
                newValue.push(element.substr(0, 1));
            });
            return newValue.join('');
        }
        return null;
    }
}
FirstLetterSplit.decorators = [
    { type: Pipe, args: [{ name: 'firstLetterSplit' },] }
];

const Validators = [
    DateValidator,
    CpfValidator,
    EmailValidator,
    NameValidator,
];
const Pipes = [
    ResumeNames,
    FirstLetterSplit
];
class EmdevToolkitModule {
}
EmdevToolkitModule.decorators = [
    { type: NgModule, args: [{
                declarations: [
                    Validators,
                    Pipes
                ],
                imports: [
                    CommonModule
                ],
                exports: [
                    Validators,
                    Pipes
                ]
            },] }
];

var TypeEmailEnum;
(function (TypeEmailEnum) {
    TypeEmailEnum[TypeEmailEnum["Business"] = 0] = "Business";
    TypeEmailEnum[TypeEmailEnum["Personal"] = 1] = "Personal";
})(TypeEmailEnum || (TypeEmailEnum = {}));

var TypeGenderEnum;
(function (TypeGenderEnum) {
    TypeGenderEnum[TypeGenderEnum["male"] = 1] = "male";
    TypeGenderEnum[TypeGenderEnum["female"] = 2] = "female";
})(TypeGenderEnum || (TypeGenderEnum = {}));

var TypeLevelUser;
(function (TypeLevelUser) {
    TypeLevelUser[TypeLevelUser["superAdministrator"] = 1] = "superAdministrator";
    TypeLevelUser[TypeLevelUser["administrator"] = 2] = "administrator";
    TypeLevelUser[TypeLevelUser["manager"] = 3] = "manager";
    TypeLevelUser[TypeLevelUser["responsible"] = 4] = "responsible";
    TypeLevelUser[TypeLevelUser["user"] = 5] = "user";
})(TypeLevelUser || (TypeLevelUser = {}));

var TypeResponse;
(function (TypeResponse) {
    TypeResponse[TypeResponse["success"] = 200] = "success";
    TypeResponse[TypeResponse["created"] = 201] = "created";
    TypeResponse[TypeResponse["noContent"] = 204] = "noContent";
    TypeResponse[TypeResponse["badRequest"] = 400] = "badRequest";
    TypeResponse[TypeResponse["unauthorized"] = 401] = "unauthorized";
    TypeResponse[TypeResponse["forbidden"] = 403] = "forbidden";
    TypeResponse[TypeResponse["notFound"] = 404] = "notFound";
    TypeResponse[TypeResponse["logoutAll"] = 406] = "logoutAll";
    TypeResponse[TypeResponse["logout"] = 410] = "logout";
    TypeResponse[TypeResponse["exception"] = 500] = "exception";
    TypeResponse[TypeResponse["notImplemented"] = 501] = "notImplemented";
})(TypeResponse || (TypeResponse = {}));

var PersonTypeDocumentEnum;
(function (PersonTypeDocumentEnum) {
    PersonTypeDocumentEnum[PersonTypeDocumentEnum["CPF"] = 1] = "CPF";
})(PersonTypeDocumentEnum || (PersonTypeDocumentEnum = {}));

var PersonTypeContactEnum;
(function (PersonTypeContactEnum) {
    PersonTypeContactEnum[PersonTypeContactEnum["EMAIL_LOGIN"] = 1] = "EMAIL_LOGIN";
    PersonTypeContactEnum[PersonTypeContactEnum["EMAIL_NOTIFICATION"] = 2] = "EMAIL_NOTIFICATION";
    PersonTypeContactEnum[PersonTypeContactEnum["CELL_PHONE"] = 3] = "CELL_PHONE";
})(PersonTypeContactEnum || (PersonTypeContactEnum = {}));

class TokenModel {
}

class PageParamsModel {
    constructor() {
        this.current = 0;
        this.limit = 12;
        this.options = [5, 12, 20, 45, 60, 80, 100];
    }
}

class PageResponseModel {
    constructor() {
        this.current = 0;
        this.limit = 25;
        this.total = 0;
    }
}

class LanguageModel {
}

class SourceModel {
}

class RenewTokenModel {
}

class AppModel {
}

class AccountAppModel {
}

class NotificationsModel {
}

class AppSessionService {
    constructor() {
        this.hasUpdateUserData = new EventEmitter();
    }
    getDataToken(token) {
        if (token) {
            const buffer = token.split('.');
            if (buffer.length === 3) {
                return JSON.parse(atob(buffer[1]));
            }
        }
        return null;
    }
    goToCallback(storagePrefix, protocol, urlApp, autorization) {
        const stringSource = sessionStorage.getItem(`${storagePrefix}source`);
        let source;
        if (stringSource) {
            source = JSON.parse(stringSource);
        }
        else {
            source = {
                app: 'profile',
                url: `${protocol}profile${urlApp}`
            };
        }
        sessionStorage.removeItem(`${storagePrefix}source`);
        window.location.href = source.url + '?callback=' + autorization;
    }
    goToAppAuth(app, protocol, pathAuthenticate, urlApp, sourceUrl = null, route = 'login') {
        const source = btoa(JSON.stringify({
            app,
            url: sourceUrl
        }));
        window.location.href = `${protocol}${pathAuthenticate}${urlApp}/${route}/?source=${source}`;
    }
    goToApp(app, protocol, urlApp) {
        window.location.href = `${protocol}${app.path}${urlApp}/login/`;
    }
}
AppSessionService.decorators = [
    { type: Injectable }
];

class AppTranslateLoader extends TranslateHttpLoader {
    constructor(httpClient, prefix, suffix) {
        super(httpClient, prefix, suffix);
        this.iHttp = httpClient;
        this.iPrefix = prefix;
        this.iSuffix = suffix;
    }
    getTranslation(lang) {
        return forkJoin([
            this.iHttp.get(this.iPrefix + '/' + this.iSuffix, { params: { lang }, observe: 'body', responseType: 'json' }),
        ]).pipe(map(response => {
            return response.reduce((defaults, enums) => Object.assign(defaults, enums));
        }));
    }
}

class HttpService {
    constructor(http) {
        this.http = http;
    }
    getNormalizedParams(params) {
        params = Object.assign([], params);
        if (params !== null) {
            Object.entries(params).forEach(([key, value]) => {
                if (typeof value === 'object') {
                    params[key] = Object.values(value).join(',');
                }
            });
        }
        if (params.options !== undefined) {
            delete params.options;
        }
        return params;
    }
    get(url, params = null) {
        return this.http.get(`${url}`, { params: this.getNormalizedParams(params) });
    }
    file(url, params = null) {
        return this.http.get(url, {
            params: this.getNormalizedParams(params),
            reportProgress: true,
            observe: 'events'
        });
    }
    post(url, model, params = null) {
        return this.http.post(`${url}`, { model }, { params: this.getNormalizedParams(params) });
    }
    put(url, model, params = null) {
        return this.http.put(`${url}`, { model }, { params: this.getNormalizedParams(params) });
    }
    delete(url, data = null) {
        return this.http.delete(`${url}`, { params: this.getNormalizedParams(data) });
    }
}
HttpService.decorators = [
    { type: Injectable }
];
HttpService.ctorParameters = () => [
    { type: HttpClient }
];

/*
 * Public API Surface of toolkit
 */

/*
 * Public API Surface of toolkit
 */

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

export { AccountAppModel, AppModel, AppSessionService, AppTranslateLoader, EmdevToolkitModule, FirstLetterSplit, HttpService, LanguageModel, NotificationsModel, PageParamsModel, PageResponseModel, PersonTypeContactEnum, PersonTypeDocumentEnum, RenewTokenModel, ResumeNames, SourceModel, TokenModel, TypeEmailEnum, TypeGenderEnum, TypeLevelUser, TypeResponse, DateValidator as ɵa, CpfValidator as ɵb, EmailValidator as ɵc, NameValidator as ɵd, ResumeNames as ɵe, FirstLetterSplit as ɵf };
//# sourceMappingURL=emdev-toolkit.js.map
