"use strict";
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 (_) 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 };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.entityCtrl = exports.nestedassign = exports.entitiesCtrl = exports.fileread = exports.copytext = exports.userdata = exports.translate = exports.textarea = exports.timesince = exports.api = void 0;
var angular = require("angular");
var openflow_api_1 = require("@openiap/openflow-api");
var api = /** @class */ (function () {
    function api($rootScope, $location, WebSocketClientService) {
        this.$rootScope = $rootScope;
        this.$location = $location;
        this.WebSocketClientService = WebSocketClientService;
    }
    api.$inject = ["$rootScope", "$location", "WebSocketClientService"];
    return api;
}());
exports.api = api;
function _timeSince(timeStamp) {
    var now = new Date(), secondsPast = (now.getTime() - timeStamp.getTime()) / 1000;
    if (secondsPast < 60) {
        return parseInt(secondsPast.toString()) + 's';
    }
    if (secondsPast < 3600) {
        return parseInt((secondsPast / 60).toString()) + 'm';
    }
    if (secondsPast <= 86400) {
        return parseInt((secondsPast / 3600).toString()) + 'h';
    }
    if (secondsPast > 86400) {
        var day = timeStamp.getDate();
        var month = timeStamp.toDateString().match(/ [a-zA-Z]*/)[0].replace(" ", "");
        var year = timeStamp.getFullYear() == now.getFullYear() ? "" : " " + timeStamp.getFullYear();
        return day + " " + month + year;
    }
}
var timesince = /** @class */ (function () {
    function timesince($location, $timeout) {
        this.$location = $location;
        this.$timeout = $timeout;
        // restrict = 'E';
        this.require = 'ngModel';
        this.replace = true;
        this.link = function (scope, element, attr, ngModelCtrl) {
            scope.$watch(function () {
                if (ngModelCtrl.$viewValue === null || ngModelCtrl.$viewValue === undefined) {
                    return;
                }
                var timeStamp = ngModelCtrl.$viewValue;
                element.text(_timeSince(new Date(timeStamp)));
            });
        };
    }
    timesince.factory = function () {
        var directive = function ($location, $timeout) { return new timesince($location, $timeout); };
        directive.$inject = ['$location', '$timeout'];
        return directive;
    };
    return timesince;
}());
exports.timesince = timesince;
var textarea = /** @class */ (function () {
    function textarea($location, $timeout) {
        this.$location = $location;
        this.$timeout = $timeout;
        // restrict = 'E';
        // require = 'ngModel';
        this.replace = true;
        this.link = function (scope, element, attr, ngModelCtrl) {
            if (!element.hasClass("autogrow")) {
                // no autogrow for you today
                return;
            }
            // get possible minimum height style
            var minHeight = parseInt(window.getComputedStyle(element[0]).getPropertyValue("min-height")) || 0;
            // prevent newlines in textbox
            // element.on("keydown", function (evt) {
            //     if (evt.which === 13) {
            //         evt.preventDefault();
            //     }
            // });
            element.on("input", function (evt) {
                var contentHeight2 = this.scrollHeight;
                var firstrun = element.attr("firstrun");
                if (contentHeight2 > 1000) {
                    if (firstrun === null || firstrun === undefined) {
                        element.attr("firstrun", "false");
                    }
                    else {
                        return;
                    }
                }
                {
                    element.css({
                        paddingTop: 0,
                        height: 0,
                        minHeight: 0
                    });
                    var contentHeight = this.scrollHeight;
                    var borderHeight = this.offsetHeight;
                    element.css({
                        paddingTop: ~~Math.max(0, minHeight - contentHeight) / 2 + "px",
                        minHeight: null,
                        height: contentHeight + borderHeight + "px" // because we're using border-box
                    });
                }
            });
            // watch model changes from the outside to adjust height
            scope.$watch(attr.ngModel, trigger);
            // set initial size
            trigger();
            function trigger() {
                setTimeout(element.triggerHandler.bind(element, "input"), 1);
            }
        };
    }
    textarea.factory = function () {
        var directive = function ($location, $timeout) { return new textarea($location, $timeout); };
        directive.$inject = ['$location', '$timeout'];
        return directive;
    };
    return textarea;
}());
exports.textarea = textarea;
function getString(locale, lib, key) {
    return __awaiter(this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            return [2 /*return*/, new Promise(function (resolve) {
                    try {
                        if (locale === null || locale === undefined) {
                            return;
                        }
                        locale.ready(lib).then(function () {
                            var value = locale.getString(lib + "." + key);
                            if (value !== null && value !== undefined && value !== "") {
                                resolve(value);
                            }
                            else {
                                resolve(key);
                            }
                        });
                    }
                    catch (error) {
                    }
                })];
        });
    });
}
var global_translate_notfound = [];
var translate = /** @class */ (function () {
    function translate($location, $timeout, locale) {
        var _this = this;
        this.$location = $location;
        this.$timeout = $timeout;
        this.locale = locale;
        this.require = '?ngModel';
        this.replace = true;
        this.link = function (scope, element, attr, ngModelCtrl) {
            var calculateValue = function (value) {
                try {
                    if (value === null || value === undefined || value === "")
                        return value;
                    var lib_1 = (attr.lib ? attr.lib : "common");
                    if ((value.toString()).startsWith(lib_1 + ".")) {
                        return;
                    }
                    var key = (lib_1 + "." + value).toLowerCase();
                    var result = _this.locale.getString(key);
                    if (result.startsWith(lib_1 + ".")) {
                        result = result.slice((lib_1 + ".").length);
                    }
                    // const result = await getString(this.locale, lib, value);
                    if (result == "%%KEY_NOT_FOUND%%" || result == "") {
                        if (global_translate_notfound.indexOf(lib_1 + "." + value) === -1) {
                            global_translate_notfound.push(lib_1 + "." + value);
                            console.debug("KEY_NOT_FOUND " + lib_1 + "." + value);
                        }
                        result = value;
                    }
                    return result;
                }
                catch (error) {
                    console.error(error);
                    return "error";
                }
            };
            var lib = (attr.lib ? attr.lib : "common");
            _this.locale.ready(lib).then(function () {
                var value = null;
                if (ngModelCtrl !== null) {
                    ngModelCtrl.$formatters.push(function (value) {
                        return calculateValue(value);
                    });
                }
                else {
                    var hashCode = function (s) {
                        return s.split("").reduce(function (a, b) { a = ((a << 5) - a) + b.charCodeAt(0); return a & a; }, 0);
                    };
                    if (attr.value !== null && attr.value !== undefined && element[0].tagName !== "OPTION") {
                        value = calculateValue(attr.value);
                        attr.$set('value', value);
                    }
                    else {
                        value = element.text();
                        if (value !== null || value !== undefined) {
                            var result = calculateValue(value);
                            element.text(result);
                        }
                    }
                }
            });
        };
    }
    translate.factory = function () {
        var directive = function ($location, $timeout, locale) { return new translate($location, $timeout, locale); };
        directive.$inject = ['$location', '$timeout', 'locale'];
        return directive;
    };
    return translate;
}());
exports.translate = translate;
var userdata = /** @class */ (function () {
    function userdata() {
        this.data = {};
    }
    return userdata;
}());
exports.userdata = userdata;
var copytext = /** @class */ (function () {
    function copytext($location, $timeout, locale) {
        this.$location = $location;
        this.$timeout = $timeout;
        this.locale = locale;
        this.restrict = 'A';
        this.require = '?ngModel';
        this.link = function (scope, element, attr, ngModelCtrl) {
            console.debug("copytext", element);
            if (!ngModelCtrl)
                return;
            element.attr('unselectable', 'on');
            element.on('mousedown', function (e, eventData) {
                /* istanbul ignore else: this is for catching the jqLite testing*/
                if (eventData)
                    angular.extend(e, eventData);
                // this prevents focusout from firing on the editor when clicking toolbar buttons
                e.preventDefault();
                console.debug("Prevent mousedown");
                return false;
            });
        };
    }
    copytext.factory = function () {
        var directive = function ($location, $timeout, locale) { return new copytext($location, $timeout, locale); };
        directive.$inject = ['$location', '$timeout', 'locale'];
        return directive;
    };
    return copytext;
}());
exports.copytext = copytext;
var fileread = /** @class */ (function () {
    function fileread($location, $timeout, locale) {
        this.$location = $location;
        this.$timeout = $timeout;
        this.locale = locale;
        this.restrict = 'A';
        this.require = '?ngModel';
        this.link = function (scope, element, attr, ngModelCtrl) {
            if (!ngModelCtrl)
                return;
            ngModelCtrl.$render = function () { };
            element.bind('change', function (changeEvent) {
                var reader = new FileReader();
                reader.onload = function (loadEvent) {
                    scope.$apply(function () {
                        var base64result = loadEvent.target.result.split(',')[1];
                        ngModelCtrl.$setViewValue(base64result);
                        scope.filename = changeEvent.target.files[0].name;
                        scope.type = changeEvent.target.files[0].type;
                    });
                };
                if (changeEvent.target.files != null && changeEvent.target.files.length > 0) {
                    reader.readAsDataURL(changeEvent.target.files[0]);
                }
            }); //change
        };
    }
    fileread.factory = function () {
        var directive = function ($location, $timeout, locale) { return new fileread($location, $timeout, locale); };
        directive.$inject = ['$location', '$timeout', 'locale'];
        return directive;
    };
    return fileread;
}());
exports.fileread = fileread;
var entitiesCtrl = /** @class */ (function () {
    function entitiesCtrl($scope, $location, $routeParams, $interval, WebSocketClientService, api, userdata) {
        this.$scope = $scope;
        this.$location = $location;
        this.$routeParams = $routeParams;
        this.$interval = $interval;
        this.WebSocketClientService = WebSocketClientService;
        this.api = api;
        this.userdata = userdata;
        this.loading = false;
        this.basequery = {};
        this.baseprojection = {};
        this.collection = "entities";
        this.models = [];
        this.orderby = { _id: -1 };
        this.autorefresh = false;
        this.autorefreshinterval = 30 * 1000;
        this.pagesize = 100;
        this.autorefreshpromise = null;
        this.preloadData = null;
        this.postloadData = null;
        this.searchstring = "";
        this.searchfields = ["name"];
        this.basequeryas = null;
        this.errormessage = "";
        if (this.userdata.data != null && this.userdata.data) {
            if (this.userdata.data.basequery != null) {
                this.basequery = this.userdata.data.basequery;
                delete this.userdata.data.basequery;
            }
            if (this.userdata.data.searchstring != null) {
                this.searchstring = this.userdata.data.searchstring;
                delete this.userdata.data.searchstring;
            }
            if (this.userdata.data.basequeryas != null) {
                this.basequeryas = this.userdata.data.basequeryas;
                delete this.userdata.data.basequeryas;
            }
        }
    }
    entitiesCtrl.parseJson = function (txt, reviver, context) {
        context = context || 20;
        try {
            return JSON.parse(txt, reviver);
        }
        catch (e) {
            if (typeof txt !== "string") {
                var isEmptyArray = Array.isArray(txt) && txt.length === 0;
                var errorMessage = "Cannot parse " +
                    (isEmptyArray ? "an empty array" : String(txt));
                throw new TypeError(errorMessage);
            }
            var syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i);
            var errIdx = syntaxErr
                ? +syntaxErr[1]
                : e.message.match(/^Unexpected end of JSON.*/i)
                    ? txt.length - 1
                    : null;
            if (errIdx != null) {
                var start = errIdx <= context
                    ? 0
                    : errIdx - context;
                var end = errIdx + context >= txt.length
                    ? txt.length
                    : errIdx + context;
                e.message += " while parsing near \"" + (start === 0 ? "" : "...") + txt.slice(start, end) + (end === txt.length ? "" : "...") + "\"";
            }
            else {
                e.message += " while parsing \"" + txt.slice(0, context * 2) + "\"";
            }
            throw e;
        }
    };
    entitiesCtrl.prototype.loadData = function () {
        return __awaiter(this, void 0, void 0, function () {
            var query, finalor, i, newq, _a, error_1;
            var _this = this;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _b.trys.push([0, 2, , 3]);
                        if (this.loading == true) {
                            console.debug("allready loading data, exit");
                            return [2 /*return*/];
                        }
                        this.errormessage = "";
                        this.loading = true;
                        if (this.preloadData != null) {
                            this.preloadData();
                        }
                        query = this.basequery;
                        if (this.searchstring !== "") {
                            if (this.searchstring.indexOf("{") == 0) {
                                if (this.searchstring.lastIndexOf("}") == (this.searchstring.length - 1)) {
                                    try {
                                        query = entitiesCtrl.parseJson(this.searchstring, null, null);
                                    }
                                    catch (error) {
                                        this.errormessage = error.message ? error.message : error;
                                    }
                                }
                            }
                            else {
                                finalor = [];
                                for (i = 0; i < this.searchfields.length; i++) {
                                    newq = {};
                                    // exact match case sensitive
                                    // newq[this.searchfields[i]] = this.searchstring;
                                    // exact match case insensitive
                                    newq[this.searchfields[i]] = new RegExp(["^", this.searchstring, "$"].join(""), "i");
                                    // exact match string contains
                                    newq[this.searchfields[i]] = new RegExp([this.searchstring].join(""), "i");
                                    finalor.push(newq);
                                }
                                if (Object.keys(query).length == 0) {
                                    query = { $or: finalor.concat() };
                                }
                                else {
                                    query = { $and: [query, { $or: finalor.concat() }] };
                                }
                            }
                        }
                        _a = this;
                        return [4 /*yield*/, openflow_api_1.NoderedUtil.Query(this.collection, query, this.baseprojection, this.orderby, this.pagesize, 0, null, this.basequeryas)];
                    case 1:
                        _a.models = _b.sent();
                        this.loading = false;
                        if (this.autorefresh) {
                            if (this.models.length >= this.pagesize) {
                                // console.warn("Disabling auto refresh, result has more than pagesize entries");
                            }
                            else {
                                if (this.autorefreshpromise == null && this.searchstring === "") {
                                    //if (this.autorefreshpromise == null) {
                                    this.autorefreshpromise = this.$interval(function () {
                                        _this.loadData();
                                    }, this.autorefreshinterval);
                                    this.$scope.$on('$destroy', function () {
                                        _this.$interval.cancel(_this.autorefreshpromise);
                                    });
                                }
                            }
                        }
                        if (this.postloadData != null) {
                            this.postloadData();
                        }
                        else {
                            if (!this.$scope.$$phase) {
                                this.$scope.$apply();
                            }
                        }
                        return [3 /*break*/, 3];
                    case 2:
                        error_1 = _b.sent();
                        this.loading = false;
                        this.errormessage = JSON.stringify(error_1);
                        if (!this.$scope.$$phase) {
                            this.$scope.$apply();
                        }
                        return [3 /*break*/, 3];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    entitiesCtrl.prototype.ToggleOrder = function (field) {
        if (this.orderby[field] == undefined) {
            this.orderby = {};
        }
        if (this.orderby[field] == -1) {
            this.orderby[field] = 1;
        }
        else {
            this.orderby[field] = -1;
        }
        if (field === '_type') {
            this.orderby["type"] = this.orderby[field];
        }
        this.loadData();
    };
    entitiesCtrl.prototype.DeleteOne = function (model) {
        return __awaiter(this, void 0, void 0, function () {
            var error_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.loading = true;
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, openflow_api_1.NoderedUtil.DeleteOne(this.collection, model._id, null)];
                    case 2:
                        _a.sent();
                        this.models = this.models.filter(function (m) { return m._id !== model._id; });
                        return [3 /*break*/, 4];
                    case 3:
                        error_2 = _a.sent();
                        this.errormessage = error_2;
                        return [3 /*break*/, 4];
                    case 4:
                        this.loading = false;
                        if (!this.$scope.$$phase) {
                            this.$scope.$apply();
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    entitiesCtrl.prototype.Search = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.loadData()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    entitiesCtrl.$inject = [
        "$scope",
        "$location",
        "$routeParams",
        "$interval",
        "WebSocketClientService",
        "api",
        "userdata"
    ];
    return entitiesCtrl;
}());
exports.entitiesCtrl = entitiesCtrl;
function nestedassign(target, source) {
    if (source === null || source === undefined)
        return null;
    var keys = Object.keys(source);
    var _loop_1 = function (i) {
        var sourcekey = keys[i];
        if (Object.keys(source).find(function (targetkey) { return targetkey === sourcekey; }) !== undefined &&
            Object.keys(source).find(function (targetkey) { return targetkey === sourcekey; }) !== null
            && typeof source === "object" && typeof source[sourcekey] === "object") {
            target[sourcekey] = nestedassign(target[sourcekey], source[sourcekey]);
        }
        else {
            target[sourcekey] = source[sourcekey];
        }
    };
    for (var i = 0; i < keys.length; i++) {
        _loop_1(i);
    }
    return target;
}
exports.nestedassign = nestedassign;
var entityCtrl = /** @class */ (function () {
    function entityCtrl($scope, $location, $routeParams, $interval, WebSocketClientService, api) {
        this.$scope = $scope;
        this.$location = $location;
        this.$routeParams = $routeParams;
        this.$interval = $interval;
        this.WebSocketClientService = WebSocketClientService;
        this.api = api;
        this.loading = false;
        this.basequery = {};
        this.baseprojection = {};
        this.collection = "entities";
        this.model = null;
        this.id = null;
        this.keys = [];
        this.autorefresh = false;
        this.autorefreshinterval = 30 * 1000;
        this.autorefreshpromise = null;
        this.preloadData = null;
        this.postloadData = null;
        this.errormessage = "";
        this.id = $routeParams.id;
        this.basequery = { _id: this.id };
    }
    entityCtrl.prototype.loadData = function () {
        return __awaiter(this, void 0, void 0, function () {
            var updated, result, i, error_3;
            var _this = this;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        if (this.loading == true) {
                            console.debug("allready loading data, exit");
                            return [2 /*return*/];
                        }
                        this.errormessage = "";
                        updated = false;
                        this.loading = true;
                        if (this.preloadData != null) {
                            this.preloadData();
                        }
                        return [4 /*yield*/, openflow_api_1.NoderedUtil.Query(this.collection, this.basequery, this.baseprojection, null, 1, 0, null)];
                    case 1:
                        result = _a.sent();
                        if (result.length > 0) {
                            if (this.model == null) {
                                this.model = result[0];
                                updated = true;
                            }
                            else {
                                if (!angular.equals(this.model, result[0])) {
                                    this.model = result[0];
                                    updated = true;
                                }
                            }
                        }
                        if (updated) {
                            this.keys = Object.keys(this.model);
                            for (i = this.keys.length - 1; i >= 0; i--) {
                                if (this.keys[i].startsWith('_'))
                                    this.keys.splice(i, 1);
                            }
                        }
                        this.loading = false;
                        if (this.postloadData != null) {
                            this.postloadData();
                        }
                        else {
                            if (!this.$scope.$$phase) {
                                this.$scope.$apply();
                            }
                        }
                        if (this.autorefresh) {
                            if (this.autorefreshpromise == null) {
                                this.autorefreshpromise = this.$interval(function () {
                                    _this.loadData();
                                }, this.autorefreshinterval);
                                this.$scope.$on('$destroy', function () {
                                    _this.$interval.cancel(_this.autorefreshpromise);
                                });
                            }
                        }
                        return [3 /*break*/, 3];
                    case 2:
                        error_3 = _a.sent();
                        this.loading = false;
                        this.errormessage = JSON.stringify(error_3);
                        if (!this.$scope.$$phase) {
                            this.$scope.$apply();
                        }
                        return [3 /*break*/, 3];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    entityCtrl.$inject = [
        "$scope",
        "$location",
        "$routeParams",
        "$interval",
        "WebSocketClientService",
        "api"
    ];
    return entityCtrl;
}());
exports.entityCtrl = entityCtrl;
//# sourceMappingURL=CommonControllers.js.map