import * as i0 from '@angular/core';
import { Component, signal, LOCALE_ID, Inject, Injectable, EventEmitter, NgModule } from '@angular/core';
import * as i1 from '@angular/common/http';
import { HttpParams, HttpHeaders, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Log, UserManager } from 'oidc-client';
import { firstValueFrom, of, retry, from, throwError, Observable } from 'rxjs';
import { map, catchError, timeout, switchMap } from 'rxjs/operators';
import '@angular/localize/init';
import { registerLocaleData } from '@angular/common';
import localeDA from '@angular/common/locales/da';
import * as i1$1 from '@angular/router';

class MobicloudCoreComponent {
    constructor() { }
    ngOnInit() {
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobicloudCoreComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); }
    static { this.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "17.3.12", type: MobicloudCoreComponent, selector: "lib-mobicloud-core", ngImport: i0, template: `
    <p>
      mobicloud-core works!
    </p>
  `, isInline: true }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobicloudCoreComponent, decorators: [{
            type: Component,
            args: [{ selector: 'lib-mobicloud-core', template: `
    <p>
      mobicloud-core works!
    </p>
  ` }]
        }], ctorParameters: () => [] });

class MobiUserProfile {
    constructor(user) {
        this.user = null;
        this.user = user;
    }
    get idToken() {
        return this.user?.id_token;
    }
    get refreshToken() {
        return this.user?.refresh_token;
    }
    get accessToken() {
        return this.user?.access_token;
    }
    get tokenType() {
        return this.user?.token_type;
    }
    get tokenScope() {
        return this.user?.scope;
    }
    get tokenExpiresAt() {
        return this.user?.expires_at;
    }
    get tokenExpiresAt_Date() {
        if (this.user)
            return new Date(this.user.expires_at * 1000);
        return undefined;
    }
    get tokenExpiresIn() {
        return this.user?.expires_in;
    }
    get tokenIsExpired() {
        return this.user?.expired;
    }
    get shouldRenewToken() {
        if (this.user)
            return this.user.expires_in <= 120;
        return false;
    }
    get user_id() {
        return this.user?.profile?.sub;
    }
    get user_name() {
        return this.user?.profile?.name;
    }
    get user_username() {
        return this.user?.profile?.username;
    }
    get user_email() {
        return this.user?.profile?.email;
    }
    get user_partytype() {
        return this.user?.profile?.partytype;
    }
    get user_partyid() {
        return this.user?.profile?.partyid;
    }
    get user_partyname() {
        return this.user?.profile?.partyname;
    }
    get user_accountnumber() {
        return this.user?.profile?.account_number;
    }
    get user_authtype() {
        return this.user?.profile?.auth_type;
    }
    get user_roles() {
        return this.user?.profile?.role;
    }
    get isOrganizationAdmin() {
        if (this.user_roles)
            return this.user_roles?.includes('ORGADMIN');
        return false;
    }
    get isOrganizationUser() {
        if (this.user_roles)
            return this.user_roles?.includes('ORGUSER');
        return false;
    }
    get isEmployeeUser() {
        if (this.user_roles)
            return this.user_roles?.includes('EMPUSER');
        return false;
    }
    get isEmployeeMasterUser() {
        if (this.user_roles)
            return this.user_roles?.includes('EMPUSER') && this.user_roles?.includes('MASTER');
        return false;
    }
    get employeeNumber() {
        return this.user?.profile?.empl_number;
    }
    get securityRole() {
        return this.user?.profile?.security_role;
    }
    get isCustomerUser() {
        if (this.user_roles)
            return this.user_roles.includes('CUSTUSER');
        return false;
    }
    get user_customer_id() {
        return this.user?.profile?.cust_id;
    }
    get user_customer_accountnumber() {
        return this.user?.profile?.cust_account;
    }
    get user_customer_name() {
        return this.user?.profile?.cust_name;
    }
    get isVendorUser() {
        if (this.user_roles)
            return this.user_roles.includes('VENDUSER');
        return false;
    }
    get isMasterUser() {
        if (this.user_roles)
            return this.user_roles.includes('MASTER');
        return false;
    }
    get isMasterAdmin() {
        if (this.user_roles)
            return this.user_roles.includes('MASTERADMIN');
        return false;
    }
    get user_vendor_id() {
        return this.user?.profile?.vend_id;
    }
    get user_vendor_accountnumber() {
        return this.user?.profile?.vend_account;
    }
    get user_vendor_name() {
        return this.user?.profile?.vend_name;
    }
    get isB2BUser() {
        return this.isCustomerUser || this.isVendorUser;
    }
}

class ApplicationDetails {
}
class CompanyCurrency {
}
var EmployeeSecurityRoleType;
(function (EmployeeSecurityRoleType) {
    EmployeeSecurityRoleType["None"] = "None";
    EmployeeSecurityRoleType["SuperUser"] = "SuperUser";
    EmployeeSecurityRoleType["Accountant"] = "Accountant";
    EmployeeSecurityRoleType["Admin"] = "Admin";
})(EmployeeSecurityRoleType || (EmployeeSecurityRoleType = {}));
class ServicePlanningSetting {
}
class DefaultDashboardSlideShowSetting {
}
var TaskPartApproveMode;
(function (TaskPartApproveMode) {
    TaskPartApproveMode["None"] = "None";
    TaskPartApproveMode["Posted"] = "Posted";
    TaskPartApproveMode["CreateReport"] = "CreateReport";
    TaskPartApproveMode["SendEmail"] = "SendEmail";
    TaskPartApproveMode["CreateReportSendEmail"] = "CreateReportSendEmail";
})(TaskPartApproveMode || (TaskPartApproveMode = {}));
class WmsLocationSetting {
}
class JournalSetting {
}
class ProductionSetting {
}
var ProductionSettingMrpLevel;
(function (ProductionSettingMrpLevel) {
    ProductionSettingMrpLevel["MRP_I"] = "MRP_I";
    ProductionSettingMrpLevel["MRP_II"] = "MRP_II";
    ProductionSettingMrpLevel["MRP_III"] = "MRP_III";
})(ProductionSettingMrpLevel || (ProductionSettingMrpLevel = {}));
class WebshipperSetting {
}
class InventorySetting {
}
var WebshipperPackageWeightMode;
(function (WebshipperPackageWeightMode) {
    WebshipperPackageWeightMode["PackageFixed"] = "PackageFixed";
    WebshipperPackageWeightMode["ItemsWeight"] = "ItemsWeight";
})(WebshipperPackageWeightMode || (WebshipperPackageWeightMode = {}));
class ModuleSetting {
}
class ProfileDetails {
}
class ProfileImage {
}
var MapProvider;
(function (MapProvider) {
    MapProvider["None"] = "None";
    MapProvider["Bing"] = "Bing";
    MapProvider["Google"] = "Google";
})(MapProvider || (MapProvider = {}));
class CloudApplicationInfo {
}
class DataApplicationInfo {
}

class MobicloudConfigService {
    constructor(http, injector, localeId) {
        this.http = http;
        this.injector = injector;
        this.localeId = localeId;
        this._config_name = '';
        this._app_name = '';
        this._app_title = '';
        this._environment = '';
        this._default_api_baseurl = '';
        this._default_taskscheduler_baseurl = '';
        this._host_url = '';
        this._host_url_en = '';
        this._oidc_authority = '';
        this._oidc_client_id = '';
        this._oidc_client_secret = '';
        this._oidc_response_type = '';
        this._oidc_scopes = '';
        this._oidc_log = false;
        this._log_httptrafic = 0;
        this._themes_enabled = false;
        this.currentLocaleId = signal('');
        this.languageName = signal('');
        this.AppInjector = injector;
        console.log("Application Language:", this.CurrentLanguage);
        if (this.localeId == "da") {
            registerLocaleData(localeDA, 'da');
        }
        this.currentLocaleId.set(this.localeId);
        this.languageName.set(this.getLanguageName(this.localeId));
    }
    checkIfConfigFileExists(config_file) {
        const timestamp = Date.now();
        return firstValueFrom(this.http.head(`./assets/${config_file}?t=${timestamp}`).pipe(map(() => true), catchError(() => of(false))));
    }
    async getConfigData(config_file) {
        const config_file_url = await this.checkIfConfigFileExists('app.config.runtime.json')
            ? './assets/app.config.runtime.json'
            : `./assets/${config_file}`;
        const configdata = await firstValueFrom(this.http.get(`${config_file_url}?t=${Date.now()}`));
        Object.assign(this, configdata);
        return configdata;
    }
    getLanguageName(locale) {
        if (locale == "da") {
            return $localize `:@@LanguageName-da:Danish`;
        }
        else {
            return $localize `:@@LanguageName-en-US:English`;
        }
    }
    get CurrentLanguage() {
        if (this.localeId == "da") {
            return "DK";
        }
        else if (this.localeId == "en-US") {
            return "US";
        }
        else {
            return this.localeId;
        }
    }
    getSupportedLanguages() {
        const languages = [{ LocaleId: 'da', LanguageName: this.getLanguageName('da'), FlagCode: 'DK' }, { LocaleId: 'en-US', LanguageName: this.getLanguageName('en-US'), FlagCode: 'GB' }];
        return languages;
    }
    getApiSiteUrl() {
        return `${this._default_api_baseurl}`;
    }
    getTaskschedulerUrl() {
        return `${this._default_taskscheduler_baseurl}`;
    }
    getApiBaseUrl() {
        return `${this.getApiSiteUrl()}api/`;
    }
    getMobiManagementDataUrl() {
        return `${this.getApiBaseUrl()}mobimanagement/`;
    }
    getRepositoryUrl() {
        return `${this.getApiBaseUrl()}repository/`;
    }
    get config_name() {
        return this._config_name;
    }
    get app_name() {
        return this._app_name;
    }
    get app_title() {
        return this._app_title;
    }
    get environment() {
        return this._environment;
    }
    get oidc_authority() {
        return this._oidc_authority;
    }
    get oidc_client_id() {
        return this._oidc_client_id;
    }
    get oidc_client_secret() {
        return this._oidc_client_secret;
    }
    get host_url() {
        return this._host_url;
    }
    get host_url_en() {
        return this._host_url_en;
    }
    get oidc_base_url() {
        if (this.localeId == "da") {
            return this.host_url;
        }
        else {
            return this.host_url_en;
        }
    }
    get oidc_redirect_uri() {
        return `${this.oidc_base_url}signin-callback`;
    }
    get oidc_redirect_silent_uri() {
        return `${this.oidc_base_url}signin-silent-callback`;
    }
    get oidc_post_logout_redirect_uri() {
        return `${this.oidc_base_url}signout-callback`;
    }
    get oidc_response_type() {
        return this._oidc_response_type;
    }
    get oidc_scopes() {
        return this._oidc_scopes;
    }
    get oidc_log() {
        return this._oidc_log;
    }
    get log_httptrafic() {
        return this._log_httptrafic;
    }
    get themes_enabled() {
        return this._themes_enabled;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobicloudConfigService, deps: [{ token: i1.HttpClient }, { token: i0.Injector }, { token: LOCALE_ID }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobicloudConfigService, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobicloudConfigService, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root'
                }]
        }], ctorParameters: () => [{ type: i1.HttpClient }, { type: i0.Injector }, { type: undefined, decorators: [{
                    type: Inject,
                    args: [LOCALE_ID]
                }] }] });

class MobicloudCoreService {
    constructor(httpClient, configService) {
        this.httpClient = httpClient;
        this.configService = configService;
        this._appVersion = '';
        this._appName = '';
        this._appTitle = '';
        this.require_Organization = true;
        this.require_Customer = false;
        this.require_Vendor = false;
        this.user = signal(null);
        this.mobiUserProfile = signal(undefined);
        this.applicationDetails = signal(undefined);
        this.profileDetails = signal(undefined);
        this.countries = signal(undefined);
        this.UserChanged = new EventEmitter();
        this.SecurityRolePriorityMap = {
            [EmployeeSecurityRoleType.None]: 0,
            [EmployeeSecurityRoleType.SuperUser]: 1,
            [EmployeeSecurityRoleType.Accountant]: 2,
            [EmployeeSecurityRoleType.Admin]: 3
        };
        this.usermanager_UserLoaded = this.usermanager_UserLoaded.bind(this);
        this.usermanager_UserUnloaded = this.usermanager_UserUnloaded.bind(this);
        if (this.configService.oidc_log) {
            Log.logger = console;
            Log.level = Log.DEBUG;
        }
        this.manager = new UserManager({
            authority: configService.oidc_authority,
            client_id: configService.oidc_client_id,
            client_secret: configService.oidc_client_secret,
            redirect_uri: configService.oidc_redirect_uri,
            post_logout_redirect_uri: configService.oidc_post_logout_redirect_uri,
            response_type: configService.oidc_response_type,
            scope: configService.oidc_scopes,
            filterProtocolClaims: true,
            loadUserInfo: true,
            silent_redirect_uri: configService.oidc_redirect_silent_uri
        });
        this.manager.events.addUserLoaded(this.usermanager_UserLoaded);
        this.manager.events.addUserUnloaded(this.usermanager_UserUnloaded);
        if (this.configService.oidc_log) {
            this.enableOidcLogEvents();
        }
        this.manager.clearStaleState();
        this.manager.getUser().then((_user) => {
            this.user.set(_user);
            if (_user)
                this.mobiUserProfile.set(new MobiUserProfile(_user));
            else
                this.mobiUserProfile.set(undefined);
            if (this.configService.oidc_log)
                console.log("constructor::manager.getUser()", "getUser complete", _user, this.user(), this.mobiUserProfile());
            this.onUserChanged().then(() => {
                if (this.configService.oidc_log)
                    console.log("constructor::manager.getUser()", "onUserChanged complete", this.user(), this.mobiUserProfile());
            });
        });
    }
    usermanager_UserLoaded(_user) {
        this.user.set(_user);
        if (_user)
            this.mobiUserProfile.set(new MobiUserProfile(_user));
        else
            this.mobiUserProfile.set(undefined);
        if (this.configService.oidc_log) {
            console.log('User loaded', _user, this.user(), this.mobiUserProfile(), this.profileDetails());
        }
        this.onUserChanged();
    }
    usermanager_UserUnloaded() {
        this.user.set(null);
        this.mobiUserProfile.set(undefined);
        this.onUserChanged();
        if (this.configService.oidc_log) {
            console.log('User unloaded', this.user(), this.mobiUserProfile(), this.profileDetails());
        }
    }
    async onUserChanged() {
        if (this.configService.oidc_log) {
            console.log("onUserChanged", "user", this.user(), this.mobiUserProfile(), this.profileDetails());
        }
        if (this.user()) {
            let appResult = await this.getApplicationDetails();
            if (this.configService.oidc_log)
                console.log("onUserChanged", "appResult", appResult);
            let profileDetailsResult = await this.getProfileDetails();
            if (this.configService.oidc_log) {
                console.log("onUserChanged", "getProfileDetails result", profileDetailsResult);
                console.log("onUserChanged", "getProfileDetails", this.profileDetails());
            }
            if (!this.countries()) {
                let countriesResult = await this.getCountries();
                if (this.configService.oidc_log) {
                    console.log("onUserChanged", "getCountries result", countriesResult);
                    console.log("onUserChanged", "getCountries", this.countries());
                }
            }
        }
        else {
            this.mobiUserProfile.set(undefined);
            this.profileDetails.set(undefined);
            this.applicationDetails.set(undefined);
        }
        this.UserChanged.emit({ user: this.user(), profile: this.mobiUserProfile(), profileDetails: this.profileDetails() });
    }
    async getApplicationDetails(requestTimeout = 30000) {
        if (!this.isAuthenticated()) {
            console.warn("ApplicationDetails is null, user not authenticated");
            this.applicationDetails.set(undefined);
            return undefined;
        }
        if (this.isMasterUserAuthenticated() && !this.hasMasterOrganization()) {
            console.warn("ApplicationDetails is null, MasterOrganization is not selected");
            this.applicationDetails.set(undefined);
            return undefined;
        }
        try {
            const url = `${this.configService.getApiBaseUrl()}ApplicationDetails`;
            const params = new HttpParams()
                .set('key', this.configService.app_name)
                .set('env', this.configService.environment);
            const appDetails = await firstValueFrom(this.httpClient.get(url, { params }).pipe(timeout(requestTimeout), retry({
                count: 2,
                delay: 1000,
                resetOnSuccess: true
            })));
            this.applicationDetails.set(appDetails);
            return appDetails;
        }
        catch (error) {
            console.error("getApplicationDetails error:", error);
            this.applicationDetails.set(undefined);
            throw error;
        }
    }
    async getCountries() {
        const url = `${this.configService.getMobiManagementDataUrl()}Country`;
        try {
            const result = await firstValueFrom(this.httpClient.get(url, {
                params: {
                    '$filter': 'enabled eq true',
                    '$orderby': 'Name',
                    '$select': 'code2,Name,LocalName,TradeArea,Shipping_Require_State'
                }
            }).pipe(timeout(15000), retry({
                count: 2,
                delay: 1000,
                resetOnSuccess: true
            })));
            const countries_map = new Map(result.value.map((country) => [country.Code2 ?? '', country]));
            this.countries.set(countries_map);
            return countries_map;
        }
        catch (error) {
            console.error(error);
            throw error;
        }
    }
    async getProfileDetails(requestTimeout = 30000) {
        if (!this.isAuthenticated() || !this.mobiUserProfile()?.user_id) {
            if (this.configService.oidc_log) {
                let profile = this.mobiUserProfile();
                console.log("getProfileDetails", "no user", profile);
            }
            this.profileDetails.set(undefined);
            return undefined;
        }
        let url;
        let orgid_override;
        if (this.mobiUserProfile()?.isEmployeeUser) {
            if (this.mobiUserProfile()?.isEmployeeMasterUser) {
                let user_org_id = this.mobiUserProfile()?.user_partyid?.toLowerCase();
                if (user_org_id != undefined) {
                    orgid_override = user_org_id;
                }
                if (this.configService.oidc_log) {
                    console.log("getProfileDetails", "isEmployeeMasterUser", user_org_id, orgid_override);
                }
            }
            url = `${this.configService.getMobiManagementDataUrl()}employee(${this.mobiUserProfile()?.user_id})?$expand=Image($select=StorageAccountName,BlobContainerName,BlobName)`;
        }
        else if (this.mobiUserProfile()?.isCustomerUser) {
            url = `${this.configService.getMobiManagementDataUrl()}customeruser(${this.mobiUserProfile()?.user_id})?$expand=Image($select=StorageAccountName,BlobContainerName,BlobName)`;
        }
        else if (this.mobiUserProfile()?.isVendorUser) {
            url = `${this.configService.getMobiManagementDataUrl()}vendoruser(${this.mobiUserProfile()?.user_id})?$expand=Image($select=StorageAccountName,BlobContainerName,BlobName)`;
        }
        if (!url) {
            if (this.configService.oidc_log) {
                let profile = this.mobiUserProfile();
                console.log("getProfileDetails", "no url", profile);
            }
            this.profileDetails.set(undefined);
            return undefined;
        }
        try {
            let headers = new HttpHeaders();
            if (orgid_override) {
                headers = headers.set("OrganizationId", orgid_override);
            }
            if (this.configService.oidc_log) {
                console.log("getProfileDetails", "url", url);
                console.log("getProfileDetails", "headers", headers);
            }
            const result = await firstValueFrom(this.httpClient.get(url, { headers: headers }).pipe(timeout(requestTimeout)));
            if (this.configService.oidc_log) {
                console.log("getProfileDetails", "result", result);
            }
            if (!result.value || !result.value[0]) {
                return undefined;
            }
            const _user = result.value[0];
            const _profileDetails = Object.assign(new ProfileDetails(), {
                Id: _user.Id?.toString(),
                Name: _user.Name,
                Image: _user.Image,
                User: _user
            });
            this.profileDetails.set(_profileDetails);
            if (this.configService.oidc_log) {
                console.log("getProfileDetails", "profileDetails", _profileDetails);
            }
            return _profileDetails;
        }
        catch (error) {
            console.error("getProfileDetails error:", error);
            this.profileDetails.set(undefined);
            return undefined;
        }
    }
    async signIn(redirectUrl) {
        if (this.configService.oidc_log) {
            console.log("signIn", redirectUrl);
        }
        let result = await this.manager?.signinRedirect({ data: { redirectUrl: redirectUrl } }).catch((reason) => {
            console.error("signIn failed:", reason, this.user(), this.mobiUserProfile());
            return new Error(reason);
        });
        if (this.configService.oidc_log) {
            console.log("signIn", "result", result, this.user(), this.mobiUserProfile());
        }
        return result;
    }
    async completeSignIn() {
        let _user = await this.manager?.signinRedirectCallback() ?? null;
        if (this.configService.oidc_log) {
            console.log("completeSignIn", _user, this.user(), this.mobiUserProfile());
        }
        return _user;
    }
    async signInSilent() {
        if (this.configService.oidc_log) {
            console.log("signInSilent");
        }
        let result = await this.manager?.signinSilent().then((_user) => {
            if (this.configService.oidc_log) {
                console.log("signInSilent", "result", _user, this.user(), this.mobiUserProfile());
            }
            this.onSignedInSilent(_user);
        }).catch((reason) => {
            console.error("signInSilent failed:", reason, this.user(), this.mobiUserProfile());
            return new Error(reason);
        });
        if (this.configService.oidc_log) {
            console.log("signInSilent", "result", result, this.user(), this.mobiUserProfile());
        }
        return result;
    }
    onSignedInSilent(_user) {
        if (this.configService.oidc_log) {
            console.log("onSignedInSilent", _user, this.user(), this.mobiUserProfile());
        }
    }
    async completeSilentSignIn() {
        if (this.configService.oidc_log) {
            console.log("completeSilentSignIn", this.user(), this.mobiUserProfile());
        }
        let result = await this.manager?.signinSilentCallback();
        if (this.configService.oidc_log) {
            console.log("signInSilent", "result", result, this.user(), this.mobiUserProfile());
        }
        return result;
    }
    async signout() {
        if (this.configService.oidc_log) {
            console.log("signout", this.user(), this.mobiUserProfile());
        }
        return await this.manager?.signoutRedirect();
    }
    async completeSignout() {
        if (this.configService.oidc_log) {
            console.log("completeSignout", this.user(), this.mobiUserProfile());
        }
    }
    enableOidcLogEvents() {
        if (this.manager) {
            this.manager.events.addUserSignedIn(() => {
                console.log('User signed in...');
            });
            this.manager.events.addAccessTokenExpiring(() => {
                console.log('Access token expiring...');
            });
            this.manager.events.addAccessTokenExpired(() => {
                console.log('Access token expired');
            });
            this.manager.events.addSilentRenewError((error) => {
                console.error('Silent renew error:', error);
            });
            this.manager.events.addUserSignedOut(() => {
                console.log('User signed out from identity server');
                console.trace('User signed out stack trace');
            });
            this.manager.events.removeUserSignedOut(() => {
                console.log('removeUserSignedOut called');
            });
            this.manager.events.addUserSessionChanged(() => {
                console.log('addUserSessionChanged called');
            });
            this.manager.events.removeUserSessionChanged(() => {
                console.log('removeUserSessionChanged called');
            });
        }
    }
    isAuthenticated() {
        return this.user() != null && !this.user()?.expired;
    }
    isOrganizationAuthenticated() {
        return this.isAuthenticated() && this.mobiUserProfile() != null && (this.mobiUserProfile()?.isOrganizationUser || this.mobiUserProfile()?.isOrganizationAdmin || this.mobiUserProfile()?.isEmployeeUser);
    }
    isMasterOrganizationAuthenticated() {
        return this.isAuthenticated() && (this.mobiUserProfile() != null && (this.mobiUserProfile()?.isOrganizationUser || this.mobiUserProfile()?.isOrganizationAdmin || this.mobiUserProfile()?.isEmployeeUser)) || this.isMasterUserAuthenticated();
    }
    isOrganizationUserAuthenticated() {
        return this.isAuthenticated() && this.mobiUserProfile() != null && (this.mobiUserProfile()?.isOrganizationUser || this.mobiUserProfile()?.isOrganizationAdmin);
    }
    isMasterOrganizationUserAuthenticated() {
        return this.isAuthenticated() && (this.mobiUserProfile() != null && (this.mobiUserProfile()?.isOrganizationUser || this.mobiUserProfile()?.isOrganizationAdmin)) || this.isMasterUserAuthenticated();
    }
    isMasterOrganizationAdminAuthenticated() {
        return this.isAuthenticated() && (this.mobiUserProfile() != null && (this.mobiUserProfile()?.isOrganizationAdmin)) || this.isMasterUserAuthenticated();
    }
    isEmployeeAuthenticated() {
        return this.isAuthenticated() && this.mobiUserProfile() != null && (this.mobiUserProfile()?.isOrganizationUser || this.mobiUserProfile()?.isOrganizationAdmin || this.mobiUserProfile()?.isEmployeeUser);
    }
    isEmployeeMasterUserAuthenticated() {
        return this.isAuthenticated() && this.mobiUserProfile() != null && (this.mobiUserProfile()?.isEmployeeMasterUser);
    }
    isMasterEmployeeAuthenticated() {
        return this.isAuthenticated() && (this.mobiUserProfile() != null && (this.mobiUserProfile()?.isOrganizationUser || this.mobiUserProfile()?.isOrganizationAdmin || this.mobiUserProfile()?.isEmployeeUser)) || this.isMasterUserAuthenticated();
    }
    isCustomerUserAuthenticated() {
        return this.isAuthenticated() && this.mobiUserProfile() != null && (this.mobiUserProfile()?.isCustomerUser);
    }
    isMasterCustomerUserAuthenticated() {
        return this.isAuthenticated() && (this.mobiUserProfile() != null && (this.mobiUserProfile()?.isCustomerUser)) || this.isMasterUserAuthenticated();
    }
    isVendorUserAuthenticated() {
        return this.isAuthenticated() && this.mobiUserProfile() != null && (this.mobiUserProfile()?.isVendorUser);
    }
    isMasterVendorUserAuthenticated() {
        return this.isAuthenticated() && (this.mobiUserProfile() != null && (this.mobiUserProfile()?.isVendorUser)) || this.isMasterUserAuthenticated();
    }
    isB2BAuthenticated() {
        return this.isAuthenticated() && (this.isOrganizationAuthenticated() || this.isCustomerUserAuthenticated() || this.isVendorUserAuthenticated());
    }
    isMasterB2BAuthenticated() {
        return this.isAuthenticated() && (this.isOrganizationAuthenticated() || this.isCustomerUserAuthenticated() || this.isVendorUserAuthenticated()) || this.isMasterUserAuthenticated();
    }
    isMasterUserAuthenticated() {
        return this.isAuthenticated() && this.mobiUserProfile() != null && (this.mobiUserProfile()?.isMasterUser || this.mobiUserProfile()?.isMasterAdmin);
    }
    isMasterAdminAuthenticated() {
        return this.isAuthenticated() && this.mobiUserProfile() != null && (this.mobiUserProfile()?.isMasterAdmin);
    }
    securityRole() {
        if (this.isAuthenticated() && this.mobiUserProfile() != null && this.mobiUserProfile()?.securityRole) {
            return EmployeeSecurityRoleType[this.mobiUserProfile()?.securityRole];
        }
        return undefined;
    }
    hasMasterOrganization() {
        var strMasterOrganizationId = localStorage.getItem("MasterOrganizationId");
        if (strMasterOrganizationId && strMasterOrganizationId.length > 0) {
            return true;
        }
        else {
            return false;
        }
    }
    getMasterOrganization() {
        var strMasterOrganizationId = localStorage.getItem("MasterOrganizationId");
        return strMasterOrganizationId;
    }
    async setMasterOrganization(strMasterOrganizationId) {
        if (strMasterOrganizationId) {
            localStorage.setItem("MasterOrganizationId", strMasterOrganizationId);
            let appdetails = await this.getApplicationDetails();
            if (this.configService.oidc_log)
                console.log("setMasterOrganization", "appResult", appdetails);
        }
        else {
            this.removeMasterOrganization();
        }
    }
    removeMasterOrganization() {
        localStorage.removeItem("MasterOrganizationId");
    }
    hasMasterCustomer() {
        var strMasterCustomerId = localStorage.getItem("MasterCustomerId");
        if (strMasterCustomerId && strMasterCustomerId.length > 0) {
            return true;
        }
        else {
            return false;
        }
    }
    getMasterCustomer() {
        var strMasterCustomerId = localStorage.getItem("MasterCustomerId");
        return strMasterCustomerId;
    }
    setMasterCustomer(strMasterCustomerId) {
        if (strMasterCustomerId) {
            localStorage.setItem("MasterCustomerId", strMasterCustomerId);
        }
        else {
            this.removeMasterCustomer();
        }
    }
    removeMasterCustomer() {
        localStorage.removeItem("MasterCustomerId");
    }
    hasMasterVendor() {
        var strMasterVendorId = localStorage.getItem("MasterVendorId");
        if (strMasterVendorId && strMasterVendorId.length > 0) {
            return true;
        }
        else {
            return false;
        }
    }
    getMasterVendor() {
        var strMasterVendorId = localStorage.getItem("MasterVendorId");
        return strMasterVendorId;
    }
    setMasterVendor(strMasterVendorId) {
        if (strMasterVendorId) {
            localStorage.setItem("MasterVendorId", strMasterVendorId);
        }
        else {
            this.removeMasterVendor();
        }
    }
    removeMasterVendor() {
        localStorage.removeItem("MasterVendorId");
    }
    redirectUrl() {
        return this.user()?.state?.redirectUrl;
    }
    get accessToken() {
        return this.user()?.access_token ?? '';
    }
    get authorizationHeader() {
        return this.user()?.token_type?.concat(" ", (this.user()?.access_token ?? ''));
    }
    get tokenExpiresAt() {
        if (this.user()) {
            let expires_at = this.user()?.expires_at;
            if (expires_at)
                return new Date(expires_at * 1000);
        }
        return undefined;
    }
    get tokenValidUntil() {
        if (this.user()) {
            let expires_at = this.user()?.expires_at;
            if (expires_at)
                return new Date((expires_at - 120) * 1000);
        }
        return undefined;
    }
    get isTokenExpired() {
        if (this.user()) {
            let expires_in = this.user()?.expires_in;
            if (expires_in)
                return expires_in <= 120;
        }
        return false;
    }
    handleError(error) {
        let errorMessage = '';
        if (error && error.error && error.error.error) {
            errorMessage = error.error.error;
        }
        else if (error && error.error instanceof ErrorEvent) {
            errorMessage = error.error.message;
        }
        else {
            errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
        }
        let anyRemoved = evaluateForMasterOrganizationClearance(errorMessage);
        if (anyRemoved) {
            location.reload();
        }
        return new Error(errorMessage);
    }
    requireEmployeePermission(mobiUserProfile, callback = undefined, securityRole = EmployeeSecurityRoleType.None) {
        let valid = (mobiUserProfile.isOrganizationUser ||
            mobiUserProfile.isOrganizationAdmin ||
            (mobiUserProfile.isMasterUser || mobiUserProfile.isMasterAdmin));
        if (!valid) {
            valid = mobiUserProfile.isEmployeeUser ?? false;
            if (valid) {
                let emplSecurityRole = EmployeeSecurityRoleType.None;
                if (mobiUserProfile.securityRole) {
                    emplSecurityRole = EmployeeSecurityRoleType[mobiUserProfile.securityRole];
                }
                valid = this.SecurityRolePriorityMap[emplSecurityRole] >= this.SecurityRolePriorityMap[securityRole];
            }
        }
        if (callback) {
            callback(valid ?? false);
        }
        return valid ?? false;
    }
    requireOrganizationUser(mobiUserProfile, callback = undefined) {
        let valid = (mobiUserProfile.isOrganizationUser ||
            mobiUserProfile.isOrganizationAdmin ||
            (mobiUserProfile.isMasterUser || mobiUserProfile.isMasterAdmin));
        if (callback) {
            callback(valid ?? false);
        }
        return valid ?? false;
    }
    requireOrganizationAdmin(mobiUserProfile, callback = undefined) {
        let valid = (mobiUserProfile.isOrganizationAdmin ||
            (mobiUserProfile.isMasterUser || mobiUserProfile.isMasterAdmin));
        if (callback) {
            callback(valid ?? false);
        }
        return valid ?? false;
    }
    requireMasterPermission(mobiUserProfile, callback = undefined) {
        let valid = (mobiUserProfile.isMasterUser || mobiUserProfile.isMasterAdmin);
        if (callback) {
            callback(valid ?? false);
        }
        return valid ?? false;
    }
    requireMasterAdminPermission(mobiUserProfile, callback = undefined) {
        let valid = mobiUserProfile.isMasterAdmin;
        if (!valid) {
            let isEmployeeMaster = (mobiUserProfile.isMasterUser ?? false) && (mobiUserProfile.isEmployeeUser ?? false);
            if (isEmployeeMaster) {
                let emplSecurityRole = EmployeeSecurityRoleType.None;
                if (mobiUserProfile.securityRole) {
                    emplSecurityRole = EmployeeSecurityRoleType[mobiUserProfile.securityRole];
                }
                valid = (this.SecurityRolePriorityMap[emplSecurityRole] == this.SecurityRolePriorityMap[EmployeeSecurityRoleType.Admin]);
            }
        }
        if (callback) {
            callback(valid ?? false);
        }
        return valid ?? false;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobicloudCoreService, deps: [{ token: i1.HttpClient }, { token: MobicloudConfigService }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobicloudCoreService, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobicloudCoreService, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root'
                }]
        }], ctorParameters: () => [{ type: i1.HttpClient }, { type: MobicloudConfigService }] });
function evaluateForMasterOrganizationClearance(errorMessage) {
    let anyRemoved = false;
    if (errorMessage && (errorMessage.toString().indexOf('No Test database has been setup') >= 0 ||
        errorMessage.toString().indexOf('Organization does not exist') >= 0)) {
        let masterOrgId = localStorage.getItem("MasterOrganizationId");
        if (masterOrgId) {
            console.log("Clearing MasterOrganizationId:", masterOrgId);
            localStorage.removeItem("MasterOrganizationId");
            anyRemoved = true;
        }
        let customerId = localStorage.getItem("MasterCustomerId");
        if (customerId) {
            console.log("Clearing MasterCustomerId:", customerId);
            localStorage.removeItem("MasterCustomerId");
            anyRemoved = true;
        }
        let vendorId = localStorage.getItem("MasterVendorId");
        if (vendorId) {
            console.log("Clearing MasterVendorId:", vendorId);
            localStorage.removeItem("MasterVendorId");
            anyRemoved = true;
        }
    }
    return anyRemoved;
}

class TokenHttpInterceptor {
    constructor(configService) {
        this.configService = configService;
    }
    intercept(req, next) {
        if ((this.configService?._default_api_baseurl && req.url.includes(this.configService._default_api_baseurl)) || (this.configService?._default_taskscheduler_baseurl && req.url.includes(this.configService._default_taskscheduler_baseurl))) {
            if (this.coreService === undefined) {
                this.coreService = this.configService.AppInjector.get(MobicloudCoreService);
            }
            if (this.configService.log_httptrafic > 1) {
                console.log({ log: "token-http-interceptor request", request: req });
            }
            const language = this.configService.CurrentLanguage;
            if (language && !req.headers.has("Language")) {
                req = req.clone({
                    headers: req.headers.set("Language", language)
                });
            }
            if (language && !req.headers.has("Application")) {
                req = req.clone({
                    headers: req.headers.set("Application", this.configService._app_name)
                });
            }
            if (this.configService.log_httptrafic > 1) {
                console.log(req);
            }
            if (this.coreService && this.coreService.isAuthenticated()) {
                if (this.coreService.isTokenExpired) {
                    if (this.configService.log_httptrafic > 0)
                        console.warn({ log: "token is expired (silent signin)", tokenValidUntil: this.coreService.tokenValidUntil, tokenExpiresAt: this.coreService.tokenExpiresAt, is: this.coreService.isTokenExpired, auth_header: this.coreService.authorizationHeader, user: this.coreService.user });
                    return from(this.coreService.signInSilent()).pipe(switchMap((user) => {
                        if (this.configService.log_httptrafic > 0)
                            console.log({ log: "token renewed (adding new token)", tokenValidUntil: this.coreService?.tokenValidUntil, tokenExpiresAt: this.coreService?.tokenExpiresAt, is: this.coreService?.isTokenExpired, auth_header: this.coreService?.authorizationHeader, user: this.coreService?.user });
                        req = req.clone({ headers: req.headers.set("Authorization", this.coreService?.authorizationHeader ?? '') });
                        if (this.coreService && this.coreService.require_Organization && !req.headers.has("OrganizationId")) {
                            var strMasterOrganizationId = this.coreService.getMasterOrganization();
                            if (strMasterOrganizationId && strMasterOrganizationId.length > 0) {
                                req = req.clone({ headers: req.headers.set("OrganizationId", strMasterOrganizationId) });
                            }
                        }
                        if (this.coreService && this.coreService.require_Customer && !req.headers.has("CustomerId")) {
                            var strMasterCustomerId = this.coreService.getMasterCustomer();
                            if (strMasterCustomerId && strMasterCustomerId.length > 0) {
                                req = req.clone({ headers: req.headers.set("CustomerId", strMasterCustomerId) });
                            }
                        }
                        if (this.coreService && this.coreService.require_Vendor && !req.headers.has("VendorId")) {
                            var strMasterVendorId = this.coreService.getMasterVendor();
                            if (strMasterVendorId && strMasterVendorId.length > 0) {
                                req = req.clone({ headers: req.headers.set("VendorId", strMasterVendorId) });
                            }
                        }
                        return next.handle(req);
                    }));
                }
                else {
                    if (this.configService.log_httptrafic > 0)
                        console.log({ log: "token not expired", tokenValidUntil: this.coreService.tokenValidUntil, tokenExpiresAt: this.coreService.tokenExpiresAt, is: this.coreService.isTokenExpired, auth_header: this.coreService.authorizationHeader, user: this.coreService.user });
                    if (!req.headers.has("Authorization")) {
                        req = req.clone({ headers: req.headers.set("Authorization", this.coreService.authorizationHeader ?? '') });
                    }
                    if (this.coreService && this.coreService.require_Organization && !req.headers.has("OrganizationId")) {
                        var strMasterOrganizationId = this.coreService.getMasterOrganization();
                        if (strMasterOrganizationId && strMasterOrganizationId.length > 0) {
                            req = req.clone({ headers: req.headers.set("OrganizationId", strMasterOrganizationId) });
                        }
                    }
                    if (this.coreService && this.coreService.require_Customer && !req.headers.has("CustomerId")) {
                        var strMasterCustomerId = this.coreService.getMasterCustomer();
                        if (strMasterCustomerId && strMasterCustomerId.length > 0) {
                            req = req.clone({ headers: req.headers.set("CustomerId", strMasterCustomerId) });
                        }
                    }
                    if (this.coreService && this.coreService.require_Vendor && !req.headers.has("VendorId")) {
                        var strMasterVendorId = this.coreService.getMasterVendor();
                        if (strMasterVendorId && strMasterVendorId.length > 0) {
                            req = req.clone({ headers: req.headers.set("VendorId", strMasterVendorId) });
                        }
                    }
                    return next.handle(req);
                }
            }
            else {
                if (this.configService.log_httptrafic > 0)
                    console.log({ log: "user not athenticated", tokenValidUntil: this.coreService.tokenValidUntil, tokenExpiresAt: this.coreService.tokenExpiresAt, is: this.coreService.isTokenExpired, auth_header: this.coreService.authorizationHeader, user: this.coreService.user });
                return next.handle(req);
            }
        }
        else {
            if (this.configService.log_httptrafic > 1)
                console.log("not app request: ", req);
            return next.handle(req);
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: TokenHttpInterceptor, deps: [{ token: MobicloudConfigService }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: TokenHttpInterceptor }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: TokenHttpInterceptor, decorators: [{
            type: Injectable
        }], ctorParameters: () => [{ type: MobicloudConfigService }] });

class UsernameValidator {
    constructor(httpClient, coreService) {
        this.httpClient = httpClient;
        this.coreService = coreService;
    }
    checkUsername(control) {
        clearTimeout(this.debouncer);
        return new Promise(resolve => {
            this.debouncer = setTimeout(() => {
                let parameterString = `?username=${control.value}`;
                if (this.currentUserId) {
                    parameterString += `&currentUserId=${this.currentUserId}`;
                }
                this.executeFunction(parameterString).then(response => {
                    response.subscribe((result) => {
                        if (result) {
                            resolve({
                                "usernametaken": true
                            });
                        }
                        else {
                            resolve(null);
                        }
                    });
                }),
                    (err) => {
                        resolve({ 'usernametaken': true });
                    };
            }, 1000);
        });
    }
    async executeFunction(parameterString = '', requestTimeout = 30000) {
        console.log(`${this.coreService.configService.getMobiManagementDataUrl()}Employee/UsernameTaken()${parameterString}`);
        return this.httpClient.get(`${this.coreService.configService.getMobiManagementDataUrl()}Employee/UsernameTaken()${parameterString}`)
            .pipe(timeout(requestTimeout), catchError(this.handleError))
            .pipe(map(result => result['value']));
    }
    handleError(error) {
        let errorMessage = '';
        if (error && error.error && error.error.error) {
            errorMessage = error.error.error;
        }
        else if (error && error.error instanceof ErrorEvent) {
            errorMessage = error.error.message;
        }
        else {
            errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
        }
        return throwError(() => errorMessage);
    }
    async usernameValidation_devextreme(username, currentUserId) {
        const params = new URLSearchParams();
        params.set('username', username);
        if (currentUserId) {
            params.set('currentUserId', currentUserId);
        }
        const url = `${this.coreService.configService.getMobiManagementDataUrl()}Employee/UsernameTaken()?${params}`;
        try {
            const res = await firstValueFrom(this.httpClient.get(url));
            res.isValid = !res.value;
            if (res.isValid) {
                res.message = $localize `:@@ValidationText-UsernameAvailable:Username is available`;
                return res;
            }
            else {
                throw $localize `:@@ErrorText-UsernameTaken:Username is not available`;
            }
        }
        catch (error) {
            console.error(error);
            throw "Error: Unable to validate username";
        }
    }
    async usernameValidation_customer_devextreme(customerId, username, currentUserId) {
        const params = new URLSearchParams();
        params.set('username', username);
        if (currentUserId) {
            params.set('currentUserId', currentUserId);
        }
        const url = `${this.coreService.configService.getMobiManagementDataUrl()}Customer(${customerId})/UsernameTaken()?${params}`;
        try {
            const res = await firstValueFrom(this.httpClient.get(url));
            res.isValid = !res.value;
            if (res.isValid) {
                res.message = $localize `:@@ValidationText-UsernameAvailable:Username is available`;
                return res;
            }
            else {
                throw $localize `:@@ErrorText-UsernameTaken:Username is not available`;
            }
        }
        catch (error) {
            console.error(error);
            throw "Error: Unable to validate username";
        }
    }
    async usernameValidation_vendor_devextreme(vendorId, username, currentUserId) {
        const params = new URLSearchParams();
        params.set('username', username);
        if (currentUserId) {
            params.set('currentUserId', currentUserId);
        }
        const url = `${this.coreService.configService.getMobiManagementDataUrl()}Vendor(${vendorId})/UsernameTaken()?${params}`;
        try {
            const res = await firstValueFrom(this.httpClient.get(url));
            res.isValid = !res.value;
            if (res.isValid) {
                res.message = $localize `:@@ValidationText-UsernameAvailable:Username is available`;
                return res;
            }
            else {
                throw $localize `:@@ErrorText-UsernameTaken:Username is not available`;
            }
        }
        catch (error) {
            console.error(error);
            throw "Error: Unable to validate username";
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: UsernameValidator, deps: [{ token: i1.HttpClient }, { token: MobicloudCoreService }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: UsernameValidator }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: UsernameValidator, decorators: [{
            type: Injectable
        }], ctorParameters: () => [{ type: i1.HttpClient }, { type: MobicloudCoreService }] });

class MobicloudCoreModule {
    static forRoot() {
        return {
            ngModule: MobicloudCoreModule,
            providers: [
                { provide: HTTP_INTERCEPTORS, useClass: TokenHttpInterceptor, deps: [MobicloudConfigService], multi: true },
                UsernameValidator
            ]
        };
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobicloudCoreModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
    static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "17.3.12", ngImport: i0, type: MobicloudCoreModule, declarations: [MobicloudCoreComponent], exports: [MobicloudCoreComponent] }); }
    static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobicloudCoreModule }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobicloudCoreModule, decorators: [{
            type: NgModule,
            args: [{
                    declarations: [MobicloudCoreComponent],
                    imports: [],
                    exports: [MobicloudCoreComponent]
                }]
        }] });

class MobiAuthenticationGuard {
    constructor(router, coreService) {
        this.router = router;
        this.coreService = coreService;
    }
    canActivate(next, state) {
        if (this.coreService.isAuthenticated()) {
            return true;
        }
        this.coreService.signIn(state.url);
        return false;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobiAuthenticationGuard, deps: [{ token: i1$1.Router }, { token: MobicloudCoreService }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobiAuthenticationGuard, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobiAuthenticationGuard, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root'
                }]
        }], ctorParameters: () => [{ type: i1$1.Router }, { type: MobicloudCoreService }] });

class MobiOrganizationGuard {
    constructor(router, coreService) {
        this.router = router;
        this.coreService = coreService;
    }
    canActivate(next, state) {
        const userProfile = this.coreService.mobiUserProfile();
        if (!userProfile) {
            if (!this.coreService.isAuthenticated()) {
                this.coreService.signIn(state.url);
            }
            return false;
        }
        return new Observable((observer) => {
            this.coreService.requireEmployeePermission(userProfile, (valid) => {
                if (valid && this.coreService.isAuthenticated()) {
                    observer.next(true);
                    observer.complete();
                }
                else {
                    if (!this.coreService.isAuthenticated()) {
                        this.coreService.signIn(state.url);
                    }
                    observer.next(false);
                    observer.complete();
                }
            });
        });
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobiOrganizationGuard, deps: [{ token: i1$1.Router }, { token: MobicloudCoreService }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobiOrganizationGuard, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobiOrganizationGuard, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root'
                }]
        }], ctorParameters: () => [{ type: i1$1.Router }, { type: MobicloudCoreService }] });
class MobiMasterUserGuard {
    constructor(router, coreService) {
        this.router = router;
        this.coreService = coreService;
    }
    canActivate(next, state) {
        const userProfile = this.coreService.mobiUserProfile();
        if (!userProfile) {
            if (!this.coreService.isAuthenticated()) {
                this.coreService.signIn(state.url);
            }
            return false;
        }
        return new Observable((observer) => {
            this.coreService.requireMasterPermission(userProfile, (valid) => {
                if (valid && this.coreService.isAuthenticated()) {
                    observer.next(true);
                    observer.complete();
                }
                else {
                    if (!this.coreService.isAuthenticated()) {
                        this.coreService.signIn(state.url);
                    }
                    observer.next(false);
                    observer.complete();
                }
            });
        });
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobiMasterUserGuard, deps: [{ token: i1$1.Router }, { token: MobicloudCoreService }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobiMasterUserGuard, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobiMasterUserGuard, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root'
                }]
        }], ctorParameters: () => [{ type: i1$1.Router }, { type: MobicloudCoreService }] });
class MobiMasterAdminGuard {
    constructor(router, coreService) {
        this.router = router;
        this.coreService = coreService;
    }
    canActivate(next, state) {
        const userProfile = this.coreService.mobiUserProfile();
        if (!userProfile) {
            if (!this.coreService.isAuthenticated()) {
                this.coreService.signIn(state.url);
            }
            return false;
        }
        return new Observable((observer) => {
            this.coreService.requireMasterAdminPermission(userProfile, (valid) => {
                if (valid && this.coreService.isAuthenticated()) {
                    observer.next(true);
                    observer.complete();
                }
                else {
                    if (!this.coreService.isAuthenticated()) {
                        this.coreService.signIn(state.url);
                    }
                    observer.next(false);
                    observer.complete();
                }
            });
        });
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobiMasterAdminGuard, deps: [{ token: i1$1.Router }, { token: MobicloudCoreService }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobiMasterAdminGuard, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobiMasterAdminGuard, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root'
                }]
        }], ctorParameters: () => [{ type: i1$1.Router }, { type: MobicloudCoreService }] });
class MasterOrganizationGuard {
    constructor(router, coreService) {
        this.router = router;
        this.coreService = coreService;
    }
    canActivate(route, state) {
        const userProfile = this.coreService.mobiUserProfile();
        if (!userProfile) {
            if (!this.coreService.isAuthenticated()) {
                this.coreService.signIn(state.url);
            }
            return false;
        }
        return new Observable((observer) => {
            this.coreService.requireEmployeePermission(userProfile, (valid) => {
                if (valid && this.coreService.isAuthenticated()) {
                    if (this.coreService.isMasterUserAuthenticated()) {
                        const strMasterOrganizationId = localStorage.getItem("MasterOrganizationId");
                        if (strMasterOrganizationId && strMasterOrganizationId.length > 0) {
                            observer.next(true);
                            observer.complete();
                        }
                        else {
                            this.router.navigateByUrl('/selectorganization');
                            observer.next(false);
                            observer.complete();
                        }
                    }
                    else {
                        observer.next(true);
                        observer.complete();
                    }
                }
                else {
                    if (!this.coreService.isAuthenticated()) {
                        this.coreService.signIn(state.url);
                    }
                    observer.next(false);
                    observer.complete();
                }
            });
        });
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MasterOrganizationGuard, deps: [{ token: i1$1.Router }, { token: MobicloudCoreService }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MasterOrganizationGuard, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MasterOrganizationGuard, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root'
                }]
        }], ctorParameters: () => [{ type: i1$1.Router }, { type: MobicloudCoreService }] });

class MobiB2BAuthenticationGuard {
    constructor(router, coreService) {
        this.router = router;
        this.coreService = coreService;
    }
    canActivate(next, state) {
        if (this.coreService.isB2BAuthenticated()) {
            return true;
        }
        if (!this.coreService.isAuthenticated()) {
            this.coreService.signIn(state.url);
        }
        return false;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobiB2BAuthenticationGuard, deps: [{ token: i1$1.Router }, { token: MobicloudCoreService }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobiB2BAuthenticationGuard, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobiB2BAuthenticationGuard, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root'
                }]
        }], ctorParameters: () => [{ type: i1$1.Router }, { type: MobicloudCoreService }] });
class MobiCustomerUserAuthenticationGuard {
    constructor(router, coreService) {
        this.router = router;
        this.coreService = coreService;
    }
    canActivate(next, state) {
        if (this.coreService.isCustomerUserAuthenticated()) {
            return true;
        }
        if (!this.coreService.isAuthenticated()) {
            this.coreService.signIn(state.url);
        }
        return false;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobiCustomerUserAuthenticationGuard, deps: [{ token: i1$1.Router }, { token: MobicloudCoreService }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobiCustomerUserAuthenticationGuard, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobiCustomerUserAuthenticationGuard, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root'
                }]
        }], ctorParameters: () => [{ type: i1$1.Router }, { type: MobicloudCoreService }] });
class MobiVendorUserAuthenticationGuard {
    constructor(router, coreService) {
        this.router = router;
        this.coreService = coreService;
    }
    canActivate(next, state) {
        if (this.coreService.isVendorUserAuthenticated()) {
            return true;
        }
        if (!this.coreService.isAuthenticated()) {
            this.coreService.signIn(state.url);
        }
        return false;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobiVendorUserAuthenticationGuard, deps: [{ token: i1$1.Router }, { token: MobicloudCoreService }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobiVendorUserAuthenticationGuard, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: MobiVendorUserAuthenticationGuard, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root'
                }]
        }], ctorParameters: () => [{ type: i1$1.Router }, { type: MobicloudCoreService }] });

function convertToISODates_ODataValues(values, value_names) {
    for (const key in value_names) {
        if (values[value_names[key]]) {
            if (!(values[value_names[key]] instanceof Date)) {
                values[value_names[key]] = new Date(values[value_names[key]]);
            }
            values[value_names[key]] = new Date(values[value_names[key]]).toISOString();
        }
    }
}
function setZeroTime_ODataValues(values, value_names) {
    for (const key in value_names) {
        if (values[value_names[key]]) {
            if (!(values[value_names[key]] instanceof Date)) {
                values[value_names[key]] = new Date(values[value_names[key]]);
            }
            values[value_names[key]].setUTCFullYear(values[value_names[key]].getFullYear());
            values[value_names[key]].setUTCMonth(values[value_names[key]].getMonth());
            values[value_names[key]].setUTCDate(values[value_names[key]].getDate());
            values[value_names[key]].setUTCHours(0);
            values[value_names[key]].setUTCMinutes(0);
            values[value_names[key]].setUTCSeconds(0);
            values[value_names[key]].setUTCMilliseconds(0);
            values[value_names[key]] = new Date(values[value_names[key]]).toISOString();
        }
    }
}
function setZeroTime_ODataValues_original(values, value_names) {
    for (const key in value_names) {
        if (values[value_names[key]]) {
            if (!(values[value_names[key]] instanceof Date)) {
                values[value_names[key]] = new Date(values[value_names[key]]);
            }
            values[value_names[key]].setFullYear(values[value_names[key]].getFullYear());
            values[value_names[key]].setMonth(values[value_names[key]].getMonth());
            values[value_names[key]].setDate(values[value_names[key]].getDate());
            values[value_names[key]].setHours(0);
            values[value_names[key]].setMinutes(0);
            values[value_names[key]].setSeconds(0);
            values[value_names[key]].setMilliseconds(0);
        }
    }
}
function ensureDateEqual(date1, date2) {
    if (date1) {
        if (!(date1 instanceof Date)) {
            date1 = new Date(date1);
        }
        if (date2) {
            if (!(date2 instanceof Date)) {
                date2 = new Date(date2);
            }
            var start = new Date(date2);
            start.setFullYear(date1.getFullYear());
            start.setMonth(date1.getMonth());
            start.setDate(date1.getDate());
            return start;
        }
    }
    return undefined;
}
function fullNameFilterExpression_Employee(filterValue, selectedFilterOperation, field) {
    let column = this;
    let filterExpression;
    if (filterValue) {
        switch (selectedFilterOperation) {
            case 'contains': {
                if (field)
                    filterExpression = [[`${field}/FirstName`, selectedFilterOperation, filterValue], "or", [`${field}/LastName`, selectedFilterOperation, filterValue]];
                else
                    filterExpression = [[`FirstName`, selectedFilterOperation, filterValue], "or", [`LastName`, selectedFilterOperation, filterValue]];
                break;
            }
            case 'notcontains': {
                if (field)
                    filterExpression = [[`${field}/FirstName`, selectedFilterOperation, filterValue], "and", [`${field}/LastName`, selectedFilterOperation, filterValue]];
                else
                    filterExpression = [[`FirstName`, selectedFilterOperation, filterValue], "and", [`LastName`, selectedFilterOperation, filterValue]];
                break;
            }
            case 'startswith': {
                if (field)
                    filterExpression = [`${field}/FirstName`, selectedFilterOperation, filterValue];
                else
                    filterExpression = [`FirstName`, selectedFilterOperation, filterValue];
                break;
            }
            case 'endswith': {
                if (field)
                    filterExpression = [`${field}/LastName`, selectedFilterOperation, filterValue];
                else
                    filterExpression = [`LastName`, selectedFilterOperation, filterValue];
                break;
            }
            default: {
                break;
            }
        }
    }
    if (!filterExpression) {
        filterExpression = column.defaultCalculateFilterExpression.apply(column, arguments);
    }
    return filterExpression;
}
function dateFunctionFilterExpression(filterValue, selectedFilterOperation, field, odata_Function) {
    let column = this;
    let filterExpression;
    if (filterValue) {
        switch (selectedFilterOperation) {
            case '=': {
                filterExpression = [[`${odata_Function}(${field})`, selectedFilterOperation, filterValue]];
                break;
            }
            case '<>': {
                filterExpression = [[`${odata_Function}(${field})`, selectedFilterOperation, filterValue]];
                break;
            }
            case '<': {
                filterExpression = [`${odata_Function}(${field})`, selectedFilterOperation, filterValue];
                break;
            }
            case '>': {
                filterExpression = [`${odata_Function}(${field})`, selectedFilterOperation, filterValue];
                break;
            }
            default: {
                break;
            }
        }
    }
    if (!filterExpression) {
        filterExpression = column.defaultCalculateFilterExpression.apply(column, arguments);
    }
    return filterExpression;
}
function getBlobUrl(storageAccountName, blobPath) {
    const delim = blobPath.startsWith('/') ? '' : '/';
    return `https://${storageAccountName}.blob.core.windows.net${delim}${blobPath}`;
}
function getProfileImageUrl(storageAccountName, blobContainerName, blobName) {
    if (storageAccountName && blobContainerName && blobName) {
        return getBlobUrl(storageAccountName, blobContainerName + blobName);
    }
    return './assets/png/no-profile-img-32.png';
}

class LanguageInfo {
}

class ThemeInfo {
}

class Country {
}
class CountryState {
}
class CountryCity {
}
class CountryPostalCode {
}

class OrganizationInfo {
}
class StorageAccountInfo {
}

var MenuState;
(function (MenuState) {
    MenuState["OpenedNormal"] = "OpenNormal";
    MenuState["OpenCollapsed"] = "OpenCollapsed";
    MenuState["Closed"] = "Closed";
})(MenuState || (MenuState = {}));

export { ApplicationDetails, CloudApplicationInfo, CompanyCurrency, Country, CountryCity, CountryPostalCode, CountryState, DataApplicationInfo, DefaultDashboardSlideShowSetting, EmployeeSecurityRoleType, InventorySetting, JournalSetting, LanguageInfo, MapProvider, MasterOrganizationGuard, MenuState, MobiAuthenticationGuard, MobiB2BAuthenticationGuard, MobiCustomerUserAuthenticationGuard, MobiMasterAdminGuard, MobiMasterUserGuard, MobiOrganizationGuard, MobiUserProfile, MobiVendorUserAuthenticationGuard, MobicloudConfigService, MobicloudCoreComponent, MobicloudCoreModule, MobicloudCoreService, ModuleSetting, OrganizationInfo, ProductionSetting, ProductionSettingMrpLevel, ProfileDetails, ProfileImage, ServicePlanningSetting, StorageAccountInfo, TaskPartApproveMode, ThemeInfo, TokenHttpInterceptor, UsernameValidator, WebshipperPackageWeightMode, WebshipperSetting, WmsLocationSetting, convertToISODates_ODataValues, dateFunctionFilterExpression, ensureDateEqual, evaluateForMasterOrganizationClearance, fullNameFilterExpression_Employee, getBlobUrl, getProfileImageUrl, setZeroTime_ODataValues, setZeroTime_ODataValues_original };
//# sourceMappingURL=mobicloud-core.mjs.map
