/* global angular */

/**
 * angular-u-data-tools - v1.5.2 - 2023-07-14
 * @author UNION DNC cvillegas
 */
'use strict';
(function () {
    var uDataTools = angular.module('uDataTools', []);
    uDataTools.provider('uDataParamsTools', function () {
        var config = {
            page_name: 'pagina',
            page_button_class: 'btn btn-outline-secondary',
            page_current_button_class: 'btn btn-secondary',
            page_prev_text: '<',
            page_next_text: '>',
            order_name: 'ordenamiento',
            order_params_separator: '_-_',
            order_params_internal_separator: '-',
            order_icon_text_default: '<i class="fas fa-sort-amount-down"></i>',
            order_icon_text_asc: '<i class="fas fa-sort-alpha-down"></i>',
            order_icon_text_desc: '<i class="fas fa-sort-alpha-down-alt"></i>',
            order_tooltip_text_default: 'ordena a->z',
            order_tooltip_text_asc: 'ordena z->a',
            order_tooltip_text_desc: 'retira ordenamiento',
            filter_name: 'buscar',
            filter_icon_class: 'btn btn-sm btn-primary float-right ml-1',
            filter_icon_text: '<i class="fas fa-filter"></i> FILTRAR',
            filter_icon_tooltip: 'Mostrar filtros',
            filter_close_class: 'btn btn-sm btn-outline-danger float-right',
            filter_close_text: '<i class="fas fa-chevron-up"></i>',
            filter_close_tooltip: 'Ocultar',
            filter_search_class: 'btn btn-sm btn-primary ml-3',
            filter_search_text: '<i class="fas fa-search"></i> Buscar',
            filter_search_tooltip: 'Filtar',
            filter_clear_class: 'btn btn-sm btn-secondary ml-3',
            filter_clear_text: '<i class="fas fa-eraser"></i> Limpiar',
            filter_clear_tooltip: 'Limpiar'
        };
        return {
            setConfig: function (new_config) {
                config = angular.extend(config, new_config);
            },
            $get: [
                '$stateParams',
                function ($stateParams) {
                    return {
                        get_config: function (config_element) {
                            if (typeof (config[config_element]) === 'undefined') {
                                console.error('configuracion no encontrada');
                            } else {
                                return config[config_element];
                            }
                        },
                        get_actual_page_from_url: function () {
                            var page_param = $stateParams[config.page_name];
                            var actual_page = 1;
                            if (typeof (page_param) !== 'undefined') {
                                if (!isNaN(parseInt(page_param, 10))) {
                                    var p = parseInt(page_param, 10);
                                    if (p > 0) {
                                        actual_page = p;
                                    }
                                }
                            }
                            return actual_page;
                        },
                        get_order_params: function () {
                            var orders_param = $stateParams[config.order_name];
                            var order_params = [];
                            if (typeof (orders_param) !== 'undefined') {
                                var order_by_params = orders_param.split(config.order_params_separator);
                                for (var i = 0; i < order_by_params.length; i++) {
                                    var param_and_value = order_by_params[i].split(config.order_params_internal_separator);
                                    order_params.push({key: param_and_value[0], value: param_and_value[1]});
                                }
                            }
                            return order_params;
                        },
                        get_filter_params: function () {
                            var filter_params = $stateParams[config.filter_name];
                            if (typeof (filter_params) !== 'undefined') {
                                return JSON.parse(decodeURIComponent(filter_params));
                            }
                            return null;
                        },
                        get_page_order_and_filters: function () {
                            var params = [
                                {key: config.page_name, value: this.get_actual_page_from_url()},
                                {key: config.order_name, value: this.get_order_params()},
                                {key: config.filter_name, value: this.get_filter_params()}
                            ];
                            return params;
                        },
                        get_filters_from_object: function (filter_data) {
                            var filters = null;
                            if (typeof (filter_data) !== 'undefined') {
                                filters = filter_data;
                            }
                            var encoded_filters = encodeURIComponent(JSON.stringify(filters));
                            return encoded_filters;
                        },
                        get_page_order_and_filters_for_rest: function (form_model) {
                            var rest_params = '';
                            var params = this.get_page_order_and_filters();
                            rest_params += '/' + params[0].key + '/' + params[0].value;
                            if (params[1].value.length > 0) {
                                rest_params += '/' + params[1].key + '/' + encodeURIComponent(JSON.stringify(params[1].value));
                            }
                            var form_model_default = {};
                            if (typeof (form_model) !== 'undefined') {
                                for (var filter_model_key in form_model) {
                                    if (typeof (form_model[filter_model_key]) !== 'undefined') {
                                        if (form_model[filter_model_key].value !== null && form_model[filter_model_key].value !== '') {
                                            if (typeof (form_model[filter_model_key].default) !== 'undefined') {
                                                if (form_model[filter_model_key].default !== null && form_model[filter_model_key].default !== '') {
                                                    form_model_default[filter_model_key] = {value: angular.copy(form_model[filter_model_key].default)};
                                                    if (typeof (form_model[filter_model_key].alias) !== 'undefined') {
                                                        form_model_default[filter_model_key].alias = form_model[filter_model_key].alias;
                                                    }
                                                    if (typeof (form_model[filter_model_key].type) !== 'undefined') {
                                                        form_model_default[filter_model_key].type = form_model[filter_model_key].type;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (params[2].value !== null) {
                                var filters = angular.extend(form_model_default, params[2].value);
                                var filters_key_value = [];
                                for (var filter in filters) {
                                    if (filters[filter].value !== '*') {//value for all, then not added
                                        filters_key_value.push({key: ((typeof (filters[filter].alias) !== 'undefined') ? (filters[filter].alias) : filter), value: filters[filter].value, type: (typeof (filters[filter].type) !== 'undefined') ? filters[filter].type : '='});
                                    }
                                }
                                rest_params += '/' + params[2].key + '/' + encodeURIComponent(JSON.stringify(filters_key_value));
                            } else {
                                if (typeof (form_model) !== 'undefined') {
                                    var filters = form_model_default;
                                    var filters_key_value = [];
                                    for (var filter in filters) {
                                        if (filters[filter].value !== '*') {//value for all, then not added
                                            filters_key_value.push({key: ((typeof (filters[filter].alias) !== 'undefined') ? (filters[filter].alias) : filter), value: filters[filter].value, type: (typeof (filters[filter].type) !== 'undefined') ? filters[filter].type : '='});
                                        }
                                    }
                                    rest_params += '/' + params[2].key + '/' + encodeURIComponent(JSON.stringify(filters_key_value));
                                }
                            }
                            return rest_params;
                        },
                        get_filters_for_url: function (form_model) {
                            var url_params = '';
                            var filter_params = this.get_filter_params();
                            var form_model_default = {};
                            if (typeof (form_model) !== 'undefined') {
                                for (var filter_model_key in form_model) {
                                    if (typeof (form_model[filter_model_key]) !== 'undefined') {
                                        if (form_model[filter_model_key].value !== null && form_model[filter_model_key].value !== '') {
                                            if (typeof (form_model[filter_model_key].default) !== 'undefined') {
                                                if (form_model[filter_model_key].default !== null && form_model[filter_model_key].default !== '') {
                                                    form_model_default[filter_model_key] = {value: angular.copy(form_model[filter_model_key].default)};
                                                    if (typeof (form_model[filter_model_key].alias) !== 'undefined') {
                                                        form_model_default[filter_model_key].alias = form_model[filter_model_key].alias;
                                                    }
                                                    if (typeof (form_model[filter_model_key].type) !== 'undefined') {
                                                        form_model_default[filter_model_key].type = form_model[filter_model_key].type;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (filter_params !== null) {
                                var filters = angular.extend(form_model_default, filter_params);
                                var filters_key_value = [];
                                for (var filter in filters) {
                                    filters_key_value.push({key: ((typeof (filters[filter].alias) !== 'undefined') ? (filters[filter].alias) : filter), value: filters[filter].value, type: (typeof (filters[filter].type) !== 'undefined') ? filters[filter].type : '='});
                                }
                                url_params += encodeURIComponent(JSON.stringify(filters_key_value));
                            } else {
                                if (typeof (form_model) !== 'undefined') {
                                    var filters = form_model_default;
                                    var filters_key_value = [];
                                    for (var filter in filters) {
                                        filters_key_value.push({key: ((typeof (filters[filter].alias) !== 'undefined') ? (filters[filter].alias) : filter), value: filters[filter].value, type: (typeof (filters[filter].type) !== 'undefined') ? filters[filter].type : '='});
                                    }
                                    url_params += encodeURIComponent(JSON.stringify(filters_key_value));
                                }
                            }
                            return url_params;
                        }
                    };
                }
            ]
        };
    });
    ////////////////////PAGINACION
    uDataTools.directive('uDataPagination', [
        '$sce',
        'uDataParamsTools',
        function ($sce, uDataParamsTools) {
            return {
                restrict: 'A',
                scope: {
                    byPage: '=?', // read-only
                    paramName: '=?', // read-only
                    total: '=?' // read-only
                },
                template: '\
                    <a class="{{btnClass}}" ui-sref="{{prev.href}}" data-ui-sref-opts="{reload: true}" ng-if="prev.show" ng-bind-html="prev.text"></a>\
                    <a class="{{btnClass}}" ng-repeat-start="page in showPages" ui-sref="{{page.href}}" data-ui-sref-opts="{reload: true}" ng-if="(page.value && !page.current)" ng-show="params.total > params.byPage">{{page.text}}</a>\
                    <a class="{{btnCurrentClass}}" ui-sref="{{page.href}}" data-ui-sref-opts="{reload: true}" ng-if="(page.value && page.current)" ng-show="params.total > params.byPage">{{page.text}}</a>\
                    <span ng-repeat-end ng-if="!page.value" ng-show="params.total > params.byPage">&nbsp;{{page.text}}&nbsp;</span>\
                    <a class="{{btnClass}}" ui-sref="{{next.href}}" data-ui-sref-opts="{reload: true}" ng-if="next.show" ng-bind-html="next.text"></a>',
                controller: [
                    function () {
                        this.paginationParams = {
                            offset: 0,
                            total: 0,
                            byPage: 10,
                            prevText: uDataParamsTools.get_config('page_prev_text'),
                            nextText: uDataParamsTools.get_config('page_next_text')
                        };
                    }
                ],
                link: function (scope, element, attrs, controller) {
                    scope.prev = {show: false};
                    scope.next = {show: false};
                    scope.showPages = [];
                    var pageName = (typeof (attrs.paramName) !== 'undefined') ? attrs.paramName : uDataParamsTools.get_config('page_name');
                    var actualPage = uDataParamsTools.get_actual_page_from_url();
                    scope.btnClass = uDataParamsTools.get_config('page_button_class');
                    scope.btnCurrentClass = uDataParamsTools.get_config('page_current_button_class');
                    scope.params = controller.paginationParams;
                    scope.$watch('params', function (params) {
                        if (params.total > 0 && params.byPage > 0) {
                            var max = Math.ceil(params.total / params.byPage);
                            scope.showPages = get_pages(actualPage, max);
                            if (1 < actualPage) {
                                scope.prev = {show: true, text: $sce.trustAsHtml(params.prevText), href: '{' + pageName + ': ' + (actualPage - 1) + '}'};
                            } else {
                                scope.prev = {show: false};
                            }
                            if (actualPage < max) {
                                scope.next = {show: true, text: $sce.trustAsHtml(params.nextText), href: '{' + pageName + ': ' + (actualPage + 1) + '}'};
                            } else {
                                scope.next = {show: false};
                            }
                        } else {
                            scope.showPages = [];
                            scope.prev = {show: false};
                            scope.next = {show: false};
                        }
                    }, true);
                    scope.$watch('byPage', function (byPage) {
                        if (!isNaN(parseInt(byPage, 10))) {
                            var l = parseInt(byPage, 10);
                            if (l > 0) {
                                scope.params.byPage = byPage;
                            }
                        }
                    }, true);
                    scope.$watch('total', function (total) {
                        if (!isNaN(parseInt(total, 10))) {
                            var t = parseInt(total, 10);
                            if (t > 0) {
                                scope.params.total = total;
                            } else {
                                scope.params.total = 0;
                            }
                        }
                    }, true);
                    function get_pages(c, m) {
                        var current = c;
                        var last = m;
                        var delta = 2;
                        var left = current - delta;
                        var right = current + delta + 1;
                        var range = [];
                        var rangeWithDots = [];
                        var l;
                        for (var i = 1; i <= last; i++) {
                            if (i === 1 || i === last || i >= left && i < right) {
                                if (i === current) {
                                    range.push({value: i, text: i, current: true, href: '{' + pageName + ': ' + i + '}'});
                                } else {
                                    range.push({value: i, text: i, current: false, href: '{' + pageName + ': ' + i + '}'});
                                }
                            }
                        }
                        for (var _i = 0, _range = range; _i < _range.length; _i++) {
                            var _i2 = _range[_i].value;
                            if (l) {
                                if (_i2 - l === 2) {
                                    rangeWithDots.push({value: (l + 1), text: (l + 1), current: false, href: '{' + pageName + ': ' + (l + 1) + '}'});
                                } else if (_i2 - l !== 1) {
                                    rangeWithDots.push({value: false, text: '...'});
                                }
                            }
                            rangeWithDots.push(_range[_i]);
                            l = _i2;
                        }
                        return rangeWithDots;
                    }
                }
            };
        }
    ]);
    ////////////////////ORDER
    uDataTools.directive('uDataOrder', [
        '$sce',
        'uDataParamsTools',
        function ($sce, uDataParamsTools) {
            return {
                restrict: 'A',
                scope: {
                    uDataOrder: '=?' // read-only
                },
                template: '\
                    <a ng-if="order === 0" title="{{order_none.order_tooltip}}" ui-sref="{{order_none.order_url}}" data-ui-sref-opts="{reload: true}" ng-bind-html="order_none.order_icon"></a>\
                    <a ng-if="order === 1" title="{{order_asc.order_tooltip}}" ui-sref="{{order_asc.order_url}}" data-ui-sref-opts="{reload: true}" ng-bind-html="order_asc.order_icon"></a>\
                    <a ng-if="order === 2" title="{{order_desc.order_tooltip}}" ui-sref="{{order_desc.order_url}}" data-ui-sref-opts="{reload: true}" ng-bind-html="order_desc.order_icon"></a>',
                link: function (scope, element, attrs, controller) {
                    scope.order = -1;
                    scope.$watch('uDataOrder', function (uDataOrder) {
                        if (typeof (uDataOrder) === 'undefined') {
                            console.error('order object is missing');
                        } else {
                            if (typeof (uDataOrder.field) === 'undefined') {
                                console.error('property field is missing');
                            } else {
                                var order_by_params = uDataParamsTools.get_order_params();
                                var order_by_params_text = '';
                                //add other params but this
                                for (var i = 0; i < order_by_params.length; i++) {
                                    if (uDataOrder.field !== order_by_params[i]['key']) {
                                        order_by_params_text += order_by_params[i]['key'] + uDataParamsTools.get_config('order_params_internal_separator') + order_by_params[i]['value'] + uDataParamsTools.get_config('order_params_separator');
                                    }
                                }
                                var filter_params = null;
                                if (uDataParamsTools.get_filter_params() !== null) {
                                    filter_params = "'" + encodeURIComponent(JSON.stringify(uDataParamsTools.get_filter_params())) + "'";
                                }
                                //create all urls
                                scope.order_none = {
                                    order_icon: $sce.trustAsHtml(uDataParamsTools.get_config('order_icon_text_default')),
                                    order_url: "{" + uDataParamsTools.get_config('page_name') + ": 1, " + uDataParamsTools.get_config('order_name') + ": '" + order_by_params_text + uDataOrder.field + uDataParamsTools.get_config('order_params_internal_separator') + "asc', " + uDataParamsTools.get_config('filter_name') + ": " + filter_params + "}",
                                    order_tooltip: uDataParamsTools.get_config('order_tooltip_text_default')
                                };
                                scope.order_asc = {
                                    order_icon: $sce.trustAsHtml(uDataParamsTools.get_config('order_icon_text_asc')),
                                    order_url: "{" + uDataParamsTools.get_config('page_name') + ": 1, " + uDataParamsTools.get_config('order_name') + ": '" + order_by_params_text + uDataOrder.field + uDataParamsTools.get_config('order_params_internal_separator') + "desc', " + uDataParamsTools.get_config('filter_name') + ": " + filter_params + "}",
                                    order_tooltip: uDataParamsTools.get_config('order_tooltip_text_asc')
                                };
                                scope.order_desc = {
                                    order_icon: $sce.trustAsHtml(uDataParamsTools.get_config('order_icon_text_desc')),
                                    order_url: "{" + uDataParamsTools.get_config('page_name') + ": 1, " + uDataParamsTools.get_config('order_name') + ": '" + ((order_by_params_text !== '') ? (order_by_params_text.slice(0, -1 * (uDataParamsTools.get_config('order_params_separator').length))) : '') + "', " + uDataParamsTools.get_config('filter_name') + ": " + filter_params + "}",
                                    order_tooltip: uDataParamsTools.get_config('order_tooltip_text_desc')
                                };
                                //set the order from actual
                                scope.order = -1;
                                for (var i = 0; i < order_by_params.length; i++) {
                                    if (uDataOrder.field === order_by_params[i]['key']) {
                                        if (typeof (order_by_params[i]['value']) !== 'undefined') {
                                            switch (order_by_params[i]['value']) {
                                                case 'asc':
                                                    scope.order = 1;
                                                    break;
                                                case 'desc':
                                                    scope.order = 2;
                                                    break;
                                            }
                                        }
                                    }
                                }
                                if (scope.order === -1) {
                                    scope.order = 0;
                                }
                            }
                        }
                    }, true);
                }
            };
        }
    ]);
    ////////////////////FILTROS
    uDataTools.directive('uDataFilter', [
        '$sce',
        '$state',
        'uDataParamsTools',
        function ($sce, $state, uDataParamsTools) {
            return {
                restrict: 'A',
                transclude: true,
                scope: {
                    uDataTools: '=?',
                    uFormModel: '=',
                    alwaysOpen: '=?', // read-only
                    startClosed: '=?', // read-only
                    targetState: '=?' // read-only
                },
                controller: [
                    '$scope',
                    function ($scope) {
                        this.$scope = $scope;
                        $scope.filter_icon_class = $sce.trustAsHtml(uDataParamsTools.get_config('filter_icon_class'));
                        $scope.filter_icon_text = $sce.trustAsHtml(uDataParamsTools.get_config('filter_icon_text'));
                        $scope.filter_icon_tooltip = $sce.trustAsHtml(uDataParamsTools.get_config('filter_icon_tooltip'));
                        $scope.filter_close_class = $sce.trustAsHtml(uDataParamsTools.get_config('filter_close_class'));
                        $scope.filter_close_text = $sce.trustAsHtml(uDataParamsTools.get_config('filter_close_text'));
                        $scope.filter_close_tooltip = $sce.trustAsHtml(uDataParamsTools.get_config('filter_close_tooltip'));
                        $scope.filter_search_class = $sce.trustAsHtml(uDataParamsTools.get_config('filter_search_class'));
                        $scope.filter_search_text = $sce.trustAsHtml(uDataParamsTools.get_config('filter_search_text'));
                        $scope.filter_search_tooltip = $sce.trustAsHtml(uDataParamsTools.get_config('filter_search_tooltip'));
                        $scope.filter_clear_class = $sce.trustAsHtml(uDataParamsTools.get_config('filter_clear_class'));
                        $scope.filter_clear_text = $sce.trustAsHtml(uDataParamsTools.get_config('filter_clear_text'));
                        $scope.filter_clear_tooltip = $sce.trustAsHtml(uDataParamsTools.get_config('filter_clear_tooltip'));
                        $scope.show_filters = false;
                        $scope.always_open = false;
                        $scope.start_closed = false;
                        $scope.target_state = null;
                        $scope.submitFilters = function () {
                            var params_for_url = {};
                            var params_is_empty = true;
                            for (var filter_key in $scope.form_model) {
                                var filter_value = $scope.form_model[filter_key];
                                if (Array.isArray(filter_value.value)) {
                                    if (filter_value.value.length > 0) {
                                        params_for_url[filter_key] = filter_value;
                                        params_is_empty = false;
                                    }
                                } else {
                                    if (typeof (filter_value.value) !== 'undefined') {
                                        if (filter_value.value !== null && filter_value.value !== '') {
                                            params_for_url[filter_key] = filter_value;
                                            params_is_empty = false;
                                        }
                                    }
                                }
                            }
                            var url_data = {};
                            url_data[uDataParamsTools.get_config('page_name')] = 1;
                            url_data[uDataParamsTools.get_config('order_name')] = null;
                            if (params_is_empty) {
                                url_data[uDataParamsTools.get_config('filter_name')] = null;
                            } else {
                                url_data[uDataParamsTools.get_config('filter_name')] = encodeURIComponent(JSON.stringify(params_for_url));
                            }
                            if ($scope.target_state === null) {
                                $state.go($state.current, url_data, {reload: true});
                            } else {
                                $state.go(((typeof ($scope.target_state.state) !== 'undefined') ? $scope.target_state.state : $state.current), (typeof ($scope.target_state.params) !== 'undefined') ? $scope.target_state.params : url_data, {reload: true});
                            }
                        };
                        $scope.cleanFilters = function () {
                            var url_data = {};
                            url_data[uDataParamsTools.get_config('page_name')] = 1;
                            url_data[uDataParamsTools.get_config('order_name')] = null;
                            url_data[uDataParamsTools.get_config('filter_name')] = null;
                            if ($scope.target_state === null) {
                                $state.go($state.current, url_data, {reload: true});
                            } else {
                                $state.go(((typeof ($scope.target_state.state) !== 'undefined') ? $scope.target_state.state : $state.current), url_data, {reload: true});
                            }
                        };
                    }
                ],
                template: '\
                    <div>\
                        <button title="{{filter_icon_tooltip}}" class="{{filter_icon_class}}" ng-click="show_filters = true" ng-show="!show_filters && !always_open" ng-bind-html="filter_icon_text"></button>\
                        <div class="card card-filter" ng-show="show_filters || always_open">\
                            <form class="filters-form" ng-submit="submitFilters()">\
                                <div class="card-header">\
                                    <button title="{{filter_close_tooltip}}" class="{{filter_close_class}}" type="button" ng-click="show_filters = false" ng-show="!always_open" ng-bind-html="filter_close_text"></button>\
                                    <h5 class="pt-2"><i class="fas fa-filter"></i> Filtros de búsqueda</h5>\
                                </div>\
                                <div class="card-body">\
                                    <div ng-transclude></div>\
                                </div>\
                                <div class="card-footer text-right border-0">\
                                    <button title="{{filter_clear_tooltip}}" class="{{filter_clear_class}}" type="button" ng-click="cleanFilters()" ng-bind-html="filter_clear_text"></button>\
                                    <button title="{{filter_search_tooltip}}" class="{{filter_search_class}}" type="submit" ng-bind-html="filter_search_text"></button>\
                                </div>\
                            </form>\
                        </div>\
                    </div>',
                link: function (scope, element, attrs, controller) {
                    scope.form_model = null;
                    scope.$watch('alwaysOpen', function (alwaysOpen) {
                        scope.always_open = false;
                        if (typeof (alwaysOpen) !== 'undefined') {
                            if (alwaysOpen === 'true' || alwaysOpen === true) {
                                scope.always_open = true;
                            }
                        }
                    }, true);
                    scope.$watch('startClosed', function (startClosed) {
                        scope.start_closed = false;
                        if (typeof (startClosed) !== 'undefined') {
                            if (startClosed === 'true' || startClosed === true) {
                                scope.start_closed = true;
                            }
                        }
                    }, true);
                    scope.$watch('targetState', function (targetState) {
                        if (typeof (targetState) !== 'undefined') {
                            scope.target_state = targetState;
                        }
                    }, true);
                    scope.$watch('uFormModel', function (uFormModel) {
                        if (scope.form_model === null) {
                            scope.form_model = uFormModel;
                            var params_is_empty = true;
                            if (scope.target_state === null) {
                                var filter_params = uDataParamsTools.get_filter_params();
                                for (var filter_key in filter_params) {
                                    var filter_value = filter_params[filter_key];
                                    if (typeof (filter_value) !== 'undefined') {
                                        if (Array.isArray(filter_value)) {
                                            if (filter_value.length > 0) {
                                                scope.form_model[filter_key] = angular.extend(scope.form_model[filter_key], filter_value);
                                                params_is_empty = false;
                                            }
                                        } else {
                                            if (filter_value !== null && filter_value !== '') {
                                                if (typeof (scope.form_model[filter_key]) !== 'undefined') {
                                                    scope.form_model[filter_key] = angular.extend(scope.form_model[filter_key], filter_value);
                                                } else {
                                                    scope.form_model[filter_key] = filter_value;
                                                }
                                                params_is_empty = false;
                                            }
                                        }
                                    }
                                }
                            }
                            for (var filter_model_key in scope.form_model) {
                                if (typeof (scope.form_model[filter_model_key].value) === 'undefined' || scope.form_model[filter_model_key].value === null || scope.form_model[filter_model_key].value === '') {
                                    if (typeof (scope.form_model[filter_model_key].default) !== 'undefined' && scope.form_model[filter_model_key].default !== null && scope.form_model[filter_model_key].default !== '') {
                                        scope.form_model[filter_model_key].value = angular.copy(scope.form_model[filter_model_key].default);
                                    }
                                }
                            }
                            if (!scope.start_closed) {
                                scope.show_filters = !params_is_empty;
                            }
                        } else {
                            scope.form_model = uFormModel;
                        }
                    }, true);
                }
            };
        }
    ]);
    uDataTools.directive('uCheckboxList', [
        '$timeout',
        function ($timeout) {
            return {
                restrict: 'A',
                require: 'ngModel',
                scope: {
                    ngChange: '&',
                    uCheckboxList: '=?',
                    uCheckboxListText: '=?',
                    uCheckboxListClass: '=?'
                },
                template: '\
                    <div ng-class="class_list.wrapper">\
                        <div ng-repeat="checkbox_element in u_checkbox_list" ng-class="class_list.container">\
                            <label ng-class="(checkbox_element.checked) ? class_list.label_checked : class_list.label_unchecked">\
                                <input type="checkbox" ng-model="checkbox_element.checked" ng-true-value="true" ng-false-value="false" ng-class="class_list.input"/>\
                                {{checkbox_element.text}}\
                            </label>\
                        </div>\
                    </div>',
                link: function (scope, element, attrs, ngModel) {
                    scope.u_checkbox_list = [];
                    scope.class_list = {wrapper: '', container: '', label: '', input: ''};
                    var u_checkbox_list_text = '';
                    if (typeof (attrs.uCheckboxListText) === 'undefined') {
                        window.console.error('falta atributo u-checkbox-list-text');
                    } else {
                        u_checkbox_list_text = attrs.uCheckboxListText;
                    }
                    scope.$watch('uCheckboxList', function (uCheckboxList) {
                        scope.u_checkbox_list = [];
                        if (typeof (uCheckboxList) !== 'undefined') {
                            var aux = angular.copy(uCheckboxList);
                            for (var i = 0; i < aux.length; i++) {
                                scope.u_checkbox_list.push({
                                    id: aux[i].id,
                                    text: aux[i][u_checkbox_list_text]
                                });
                            }
                        }
                    }, true);
                    scope.$watch('u_checkbox_list', function (u_checkbox_list) {
                        if (Array.isArray(u_checkbox_list) && u_checkbox_list.length > 0) {
                            var ng_model = [];
                            for (var i = 0; i < u_checkbox_list.length; i++) {
                                if (typeof (u_checkbox_list[i].checked) !== 'undefined') {
                                    if (u_checkbox_list[i].checked) {
                                        ng_model.push(u_checkbox_list[i].id);
                                    }
                                }
                            }
                            ngModel.$setViewValue(ng_model);
                        }
                    }, true);
                    scope.$watch('uCheckboxListClass', function (uCheckboxListClass) {
                        scope.class_list = angular.extend(scope.class_list, uCheckboxListClass);
                    }, true);
                    ngModel.$render = function () {
                        var model_value = angular.copy(ngModel.$modelValue);
                        $timeout(function () {
                            var checkbox_list = angular.copy(scope.u_checkbox_list);
                            if (Array.isArray(model_value) && Array.isArray(checkbox_list)) {
                                for (var i = 0; i < checkbox_list.length; i++) {
                                    checkbox_list[i].checked = false;
                                }
                                for (var i = 0; i < model_value.length; i++) {
                                    for (var j = 0; j < checkbox_list.length; j++) {
                                        if (parseInt(model_value[i]) === parseInt(checkbox_list[j].id)) {
                                            checkbox_list[j].checked = true;
                                        }
                                    }
                                }
                                scope.u_checkbox_list = checkbox_list;
                            }
                        });
                    };
                }
            };
        }
    ]);
})();