var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
import { inject } from 'aurelia-framework';
import { Router } from 'aurelia-router';
import { EntityManager } from './entity-manager';
import { CustomLogger } from '../modules/custom-logger';
import * as breeze from 'breeze-client';
import { UserProfile } from '../model/common-model';
import { Config } from '../config';
import { HttpClient, json } from 'aurelia-fetch-client';
import { I18N } from 'aurelia-i18n';
import { EventAggregator } from 'aurelia-event-aggregator';
export var Datacontext = (function () {
    function Datacontext(entityManager, logger, config, router, httpClient, i18n, eventAggregator) {
        var _this = this;
        this.entityManager = entityManager;
        this.logger = logger;
        this.config = config;
        this.router = router;
        this.httpClient = httpClient;
        this.i18n = i18n;
        this.eventAggregator = eventAggregator;
        eventAggregator.subscribe('i18n:locale:changed', function (data) { return __awaiter(_this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, this.changeCurrentLangage()];
                    case 1:
                        _a.sent();
                        return [2];
                }
            });
        }); });
    }
    Object.defineProperty(Datacontext.prototype, "translatePropertyName", {
        get: function () {
            return "lang".concat(this.currentLanguage.columnIndex);
        },
        enumerable: false,
        configurable: true
    });
    Datacontext.prototype.primeData = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4, Promise.all([
                            this.corePrimeData()
                        ])];
                    case 1:
                        _a.sent();
                        return [4, this.changeCurrentLangage()];
                    case 2:
                        _a.sent();
                        return [2];
                }
            });
        });
    };
    Datacontext.prototype.changeCurrentLangage = function () {
        return __awaiter(this, void 0, void 0, function () {
            var currentLocale_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(this.config.globalConfig.configuredLanguages != null)) return [3, 2];
                        currentLocale_1 = this.i18n.getLocale();
                        if (currentLocale_1 == null)
                            currentLocale_1 = "fr";
                        this.currentLanguage = this.config.globalConfig.configuredLanguages.find(function (l) { return l.code.toLocaleLowerCase() == currentLocale_1; });
                        return [4, this.saveUserLanguage()];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2: return [2];
                }
            });
        });
    };
    Datacontext.prototype.corePrimeData = function () {
        var _this = this;
        return breeze.EntityQuery.from("PrimeData")
            .using(this.entityManager.manager)
            .execute()
            .then(function (data) {
            _this.config.globalConfig.configuredLanguages = data.results[0].languages;
            return data;
        }).catch(this.queryFailed);
    };
    Datacontext.prototype.getDistinctPropertyValues = function (tableName, propertyName, includeNullValue) {
        var _this = this;
        if (includeNullValue === void 0) { includeNullValue = true; }
        return breeze.EntityQuery.from("DistinctPropertyValues")
            .withParameters({ tableName: tableName, propertyName: propertyName, includeNullValue: includeNullValue })
            .using(this.entityManager.manager)
            .execute()
            .then(function (data) {
            return data.results;
        })
            .catch(function (reason) { return _this.queryFailed(reason); });
    };
    Datacontext.prototype.getCurrentUserProfile = function () {
        return __awaiter(this, void 0, void 0, function () {
            var data, reason_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4, breeze.EntityQuery.from("GetCurrentUser")
                                .using(this.entityManager.manager)
                                .execute()];
                    case 1:
                        data = _a.sent();
                        return [2, new UserProfile(data.results[0])];
                    case 2:
                        reason_1 = _a.sent();
                        this.queryFailed(reason_1);
                        return [3, 3];
                    case 3: return [2];
                }
            });
        });
    };
    Datacontext.prototype.queryFailed = function (error) {
        var msg = this.i18n.tr('clientExceptions.errorRetreivingData', { ns: "common" }) + ": " + error.message;
        this.logError(msg, error);
        return null;
    };
    Datacontext.prototype.log = function (msg, data, showToast) {
        this.logger.Log(msg, data, "Datacontext", showToast);
    };
    Datacontext.prototype.logError = function (msg, error) {
        this.logger.LogError(msg, error, "Datacontext", true);
    };
    Datacontext.prototype.saveUserSettings = function (userProfile) {
        return __awaiter(this, void 0, void 0, function () {
            var error_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        sessionStorage.setItem("user-settings-".concat(userProfile.id), JSON.stringify(userProfile.sanitizedSettings));
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4, this.httpClient
                                .fetch("".concat(this.config.globalConfig.breezeControllerUri, "/SaveUserSettings"), {
                                method: 'post',
                                body: json(userProfile.sanitizedSettings),
                                headers: {
                                    'Content-Type': 'application/json; charset=utf-8',
                                    'Accept': 'application/json'
                                }
                            })];
                    case 2:
                        _a.sent();
                        this.log('user settings saved successfully', null, false);
                        return [3, 4];
                    case 3:
                        error_1 = _a.sent();
                        this.log('user settings not saved', error_1, false);
                        return [3, 4];
                    case 4: return [2];
                }
            });
        });
    };
    Datacontext.prototype.saveUserLanguage = function () {
        return __awaiter(this, void 0, void 0, function () {
            var body, error_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        body = json(this.i18n.getLocale());
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4, this.httpClient
                                .fetch("".concat(this.config.globalConfig.breezeControllerUri, "/SaveUserLanguage"), {
                                method: 'post',
                                body: body,
                                headers: {
                                    'Content-Type': 'application/json; charset=utf-8',
                                    'Accept': 'application/json'
                                }
                            })];
                    case 2:
                        _a.sent();
                        this.log('user language saved successfully', null, false);
                        return [3, 4];
                    case 3:
                        error_2 = _a.sent();
                        this.log('user language not saved', error_2, false);
                        return [3, 4];
                    case 4: return [2];
                }
            });
        });
    };
    Datacontext = __decorate([
        inject(EntityManager, CustomLogger, Config, Router, HttpClient, I18N, EventAggregator),
        __metadata("design:paramtypes", [EntityManager, CustomLogger, Config, Router, HttpClient, I18N, EventAggregator])
    ], Datacontext);
    return Datacontext;
}());

//# sourceMappingURL=data-context.js.map
