Source: directives/preset/preset.js

/**
 * @ngdoc directives
 * @name Preset
 * @module s4c.directives.preset.Preset
 *
 * @description
 * `Preset` Controller da funcionalidade de Preset 
 * 
 * 
 */
(function () {
    var app = angular.module('s4c.components.preset', ['file-model'])
        .directive('s4cPreset', s4cPreset);


    app.directive('ngRightClick', function ($parse) {
        return function (scope, element, attrs) {
            var fn = $parse(attrs.ngRightClick);
            element.bind('contextmenu', function (event) {
                scope.$apply(function () {
                    event.preventDefault();
                    fn(scope, { $event: event });
                });
            });
        };
    });

    s4cPreset.$inject = [
        'Preset',
        'Modulo',
        'MapaService',
        '$mdDialog',
        'ParametrosS4C',
        '$interval',
        'CategoriaAplicacaoService',
        'FaceService',
        'FileService',
        'FileUploader',
        'MainState',
        '$timeout',
        'HdmiService',
        '$http',
        'API_ENDPOINT'
    ];

    function s4cPreset(Preset, Modulo, MapaService, $mdDialog, ParametrosS4C, $interval,
        CategoriaAplicacaoService, FaceService, FileService, FileUploader, MainState, $timeout, HdmiService, $http, API_ENDPOINT) {

        return {
            restrict: 'E',
            templateUrl: 'app/directives/preset/preset.html',
            scope: {},
            link: function ($scope, $elem, $attrs) {

                $scope.res = $scope.$root.res;

                /**
                 * @method newProperties
                 */
                function newProperties() {
                    this.filtroAtivo = false;
                    this.modulos = [];
                    this.config = Preset.config;
                    this.escolhaModulos = escolhaModulos;
                    this.removerItem = Preset.removerItem;
                    this.toogleFilter = function () {
                        this.filtroAtivo = !this.filtroAtivo;
                    }
                }

                /**
                 * @method initModulo
                 * @param {*} modulo
                 */
                $scope.initModulo = function (modulo) {

                    $timeout(function () {
                        if (ParametrosS4C.showing == true) {
                            $('#' + modulo.id + ' .barraModulo').addClass('mostraBarra');
                            $('#' + modulo.id + ' .barraModulo .md-toolbar-tools span').addClass('menuFonte');
                        }

                        $('#' + modulo.id + ' .face .wrapper').addClass('topClass');
                    }, 500);

                    Modulo.initModulo(modulo);
                    if (modulo.Face != null && modulo.Face.name == 'MODULO_MAPA') {
                        if (Preset.config.preset.mapaPosZoom != null && Preset.config.preset.mapaPosInicial != null) {
                            var newPos = new L.LatLng(Preset.config.preset.mapaPosInicial.coordinates.coordinates[0], Preset.config.preset.mapaPosInicial.coordinates.coordinates[1]);
                            setTimeout(function () { execute_(newPos); }, 2000);
                        }
                        MapaService.isLoadedMapa = true;
                        setTimeout(function () {
                            if (Preset.config.preset.mapaPosZoom != null && Preset.config.preset.mapaPosInicial != null) {
                                var newPos = new L.LatLng(Preset.config.preset.mapaPosInicial.coordinates.coordinates[0],
                                    Preset.config.preset.mapaPosInicial.coordinates.coordinates[1]);
                                MapaService.setView(newPos, Preset.config.preset.mapaPosZoom);
                            }
                        }, 2000);

                    }
                }

                /**
                 * @method execute_
                 * @param {*} newPos 
                 */
                function execute_(newPos) {
                    MapaService.setView(newPos, Preset.config.preset.mapaPosZoom);
                }

                /* cria uma instancia das propriedades pra ser usada em cada modulo, sem um afetar o outro */
                var properties = new newProperties();

                /* extende as propriedades pra cada modulo */
                angular.extend($scope, properties);

                $scope.modulosOriginais = _.cloneDeep(Preset.config.preset.PresetModulos);
                Preset.config.preset.PresetModulos.novasFaces = [];

                $scope.renderes = [];
                Preset.setModuleRenderes($scope.renderes);

                /**
                 * @method share
                 * @param {*} divId
                 */
                $scope.share = function (divId) {

                    if (ParametrosS4C.parametros.multivisConfig.length == 0) {
                        return;
                    }

                    if (ParametrosS4C.parametros.multivisConfig.length == 1) {
                        var rect = document.getElementById(divId).getBoundingClientRect();

                        var constraint = {
                            url: ParametrosS4C.parametros.multivisConfig[0].hostname.replace('https', 'wss').replace('http', 'ws'),
                            x: rect.x,
                            y: rect.y,
                            dx: rect.width,
                            dy: rect.height,
                            positionX: 0,
                            positionY: 0
                        }

                        if (!$scope.renderes[divId] || !$scope.renderes[divId][ParametrosS4C.parametros.multivisConfig[0].hostname]) {
                            var connection1 = new render.Screenshare(constraint);

                            if (!$scope.renderes[divId]) {
                                $scope.renderes[divId] = [];
                            }
                            $scope.renderes[divId][ParametrosS4C.parametros.multivisConfig[0].hostname] = connection1;
                        }

                        hideShare(divId);
                        return;
                    }

                    var confirm = $mdDialog.confirm({
                        locals: { render: render, renderes: $scope.renderes },
                        templateUrl: 'app/directives/preset/escolhaMultivis.html',
                        controller: function ($scope, $mdDialog, render, renderes) {

                            $scope.res = $scope.$root.res;
                            $scope.multivisSelecionado;
                            $scope.multivisList = ParametrosS4C.parametros.multivisConfig;
                            $scope.positionX;
                            $scope.positionY;

                            $scope.rendered = false;
                            var interval = $interval(function () {
                                if (!$scope.rendered && document.getElementById("escolhaMultivis")) {
                                    document.getElementById("escolhaMultivis").style.top = window.positionY + "px";

                                    if (window.positionX - 400 > 0) {
                                        document.getElementById("escolhaMultivis").style.left = (window.positionX - 400) + "px";
                                    } else {
                                        document.getElementById("escolhaMultivis").style.left = window.positionX + "px";
                                    }
                                    $scope.rendered = true;
                                    $interval.cancel(interval);
                                }
                            }, 30);

                            $scope.ok = function () {

                                if (!$scope.multivisSelecionado) {
                                    return;
                                }

                                var rect = document.getElementById(divId).getBoundingClientRect();

                                var constraint = {
                                    url: $scope.multivisSelecionado.hostname.replace('https', 'wss').replace('http', 'ws'),
                                    x: rect.x,
                                    y: rect.y,
                                    dx: rect.width,
                                    dy: rect.height,
                                    positionX: $scope.positionX,
                                    positionY: $scope.positionY
                                }

                                if (!renderes[divId] || !renderes[divId][$scope.multivisSelecionado.hostname]) {
                                    var connection1 = new render.Screenshare(constraint);

                                    if (!renderes[divId]) {
                                        renderes[divId] = [];
                                    }
                                    renderes[divId][$scope.multivisSelecionado.hostname] = connection1;
                                }

                                hideShare(divId);
                                $mdDialog.hide();
                            }

                            $scope.cancelar = function () {
                                $mdDialog.hide();
                            };
                        },
                        parent: angular.element(document.body)
                    });

                    $mdDialog.show(confirm).then(function () { }, function () { });
                }

                /**
                 * @method hideBar
                 * @param {*} divId
                 */
                $scope.hideBar = function (divId) {
                    $('#' + divId + ' .barraModulo').removeClass('mostraBarra');
                    $('#' + divId + ' .barraModulo .md-toolbar-tools span').removeClass('menuFonte');
                    $('#' + divId + ' .btn-action').addClass('show');
                    $('#' + divId + ' .wrapper').addClass('topClass');
                    $('#' + divId + ' .wrapper').removeClass('mt-5');
                }

                /**
                 * @method zoomClass
                 */
                $scope.zoomClass = function () {
                    let w = window.innerWidth
                    let mouseW = event.clientX
                    let classZoom
                    if(w <= 3840){
                        classZoom =  'zoom-center'
                    }else if((w > 3840) & (mouseW > w/2)){
                        classZoom =  'zoom-right'
                    }else if((w > 3840) & (mouseW < w/2)){
                        classZoom =  'zoom-left'
                    }
                    return classZoom
                }

                /**
                 * @method print
                 * @param {*} moduloId
                 */
                $scope.print = function(moduloId){
                    var webView = document.getElementById(moduloId).getElementsByTagName("webview")[0];
                    webView.print();
                }

                /**
                 * @method zoomModulo
                 * @param {*} divId
                 */
                $scope.zoomModulo = function (divId) {
                    if($('.gridster-item').hasClass($scope.zoomClass())){
                        $('.' + $scope.zoomClass()).find('.icofont-minus').addClass('d-none')
                        $('.' + $scope.zoomClass()).find('.menu-icon').not('.icofont-minus').removeClass('d-none')
                        $('.' + $scope.zoomClass()).removeClass('modulo-zoom ' + $scope.zoomClass())
                        //console.log('Ja esta aberto')
                    }
                        $('#' + divId).closest('.gridster-item').addClass(" modulo-zoom " + $scope.zoomClass())
                        $('#' + divId).find('.icofont-minus').removeClass('d-none')
                        $('#' + divId).find('.menu-icon').not('.icofont-minus').addClass('d-none')
                        setTimeout( () => MapaService.refreshMap(),500)
                }

                /**
                 * @method minusModulo
                 * @param {*} divId
                 */
                $scope.minusModulo = function (divId) {
                    $('#' + divId).closest('.gridster-item').removeClass('modulo-zoom zoom-left zoom-right zoom-center')
                    $('#' + divId).find('.md-toolbar-tools').find('.icofont-minus').addClass('d-none')
                    $('#' + divId).find('.md-toolbar-tools').find('.menu-icon').not('.icofont-minus').removeClass('d-none')
                    setTimeout( () => MapaService.refreshMap(),500)
                }

                $scope.browserItensArray = []
                /**
                 * @method showBrowserItems
                 * @param {*} divId
                 */                
                $scope.showBrowserItems = function (divId) {
                    $scope.browserItensArray[divId] = !$scope.browserItensArray[divId];
                }

                // $scope.checkIfEnterKeyWasPressed = function ($event, moduloId, address) {
                //     var keyCode = $event.which || $event.keyCode;
                //     if (keyCode === 13) {
                //         updateLink(moduloId, address);
                //     }
                // };

                /**
                 * @method checkIfEnterKeyWasPressed
                 * @param {*} $event
                 * @param {*} moduloId
                 */                 
                $scope.checkIfEnterKeyWasPressed = function ($event, moduloId) {
                    let address = "";
                    address = $('#' + moduloId + ' .addressClass').val();
                    let keyCode = $event.keyCode;
                    if (keyCode === 13) {
                        updateLink(moduloId, address);
                    }
                };

                /**
                 * @method btnIrWeb
                 * @param {*} moduloId
                 */                   
                $scope.btnIrWeb = function (moduloId) {
                    let address = $('#' + moduloId + ' .addressClass').val();
                        updateLink(moduloId, address);
                };

                /**
                 * @method reloadWebview
                 * @param {*} moduloId
                 */                       
                $scope.reloadWebview = function (moduloId) {
                    var webView = document.getElementById(moduloId).getElementsByTagName("webview")[0];
                    webView.reload();
                }

                /**
                 * @method updateLink
                 * @param {*} moduloId 
                 * @param {*} address 
                 */
                function updateLink(moduloId, address) {

                    if (address.indexOf('http://') == -1 && address.indexOf('https://') == -1) {
                        address = 'http://' + address;
                    }

                    var webView = document.getElementById(moduloId).getElementsByTagName("webview")[0];
                    if (webView.src.length > 0 && address == webView.getURL()) {
                        return;
                    }

                    webView.src = address;
                    $('#' + moduloId + ' .addressClass').val(address);

                    _.each(Preset.config.preset.PresetModulos, function (modulo) {
                        if (modulo.id == moduloId) {
                            modulo.extras = { url: address };
                        }
                    });
                }

                $scope.menu = {};
                $scope.menu.isOpen = false;
                /**
                 * @method abrirMenu
                 * @param {*} e
                 */
                $scope.abrirMenu = function (e) {
                    $scope.menu.isOpen = !$scope.menu.isOpen;
                }

                $scope.zoomNumber = [];
                $scope.divZoom = [];
                /**
                 * @method zoom
                 * @param {*} divId
                 * @param {*} zoomLevel
                 * @param {*} $event
                 */                
                $scope.zoom = function (divId, zoomLevel, $event) {

                    $event.stopPropagation();

                    if (!$scope.zoomNumber[divId]) {
                        $scope.zoomNumber[divId] = 100;
                    }

                    if (!$scope.divZoom[divId]) {
                        $scope.divZoom[divId] = 1;
                    }

                    if ($scope.divZoom[divId] + zoomLevel < -1) {
                        return;
                    }

                    zoomLevel = zoomLevel / 10;
                    $scope.divZoom[divId] += zoomLevel;

                    if (zoomLevel < 0) {
                        $scope.zoomNumber[divId] -= 10;
                    } else {
                        $scope.zoomNumber[divId] += 10;
                    }

                    //Pega a webview dentro das divs internas do modulo.
                    var document_ = document.getElementById(divId);
                    var x = document_.getElementsByTagName("webview");
                    x[0].setZoomFactor($scope.divZoom[divId]);
                }

                $scope.showNavigator = [];
                 /**
                 * @method showNavigatorBar
                 * @param {*} moduloId
                 * @param {*} $event
                 */                  
                $scope.showNavigatorBar = function (moduloId, $event) {
                    $event.stopPropagation();
                    $scope.showNavigator[moduloId] = !$scope.showNavigator[moduloId];
                }

                 /**
                 * @method forward
                 * @param {*} divId
                 * @param {*} $event
                 */                 
                $scope.forward = function (divId, $event) {

                    $event.stopPropagation();

                    var document_ = document.getElementById(divId);
                    var x = document_.getElementsByTagName("webview");

                    if (x[0].canGoForward()) {
                        x[0].goForward();
                        $('#' + divId + ' .addressClass').val(x[0].getURL());
                    }
                }

                 /**
                 * @method backward
                 * @param {*} divId
                 * @param {*} $event
                 */                     
                $scope.backward = function (divId, $event) {

                    $event.stopPropagation();

                    var document_ = document.getElementById(divId);
                    var x = document_.getElementsByTagName("webview");

                    if (x[0].canGoBack()) {
                        x[0].goBack();
                        $('#' + divId + ' .addressClass').val(x[0].getURL());
                    }
                }

                /**
                 * @method reload
                 * @param {*} divId
                 * @param {*} $event
                 */                   
                $scope.reload = function (divId, $event) {

                    $event.stopPropagation();

                    var document_ = document.getElementById(divId);
                    var x = document_.getElementsByTagName("webview");

                    x[0].reloadIgnoringCache();
                }

                /**
                 * @method hideShare
                 * @param {*} divId
                 */                 
                function hideShare(divId) {
                    $scope.cancelledArray[divId] = true;
                }

                 /**
                 * @method showShare
                 * @param {*} divId
                 */   
                function showShare(divId) {
                    $scope.cancelledArray[divId] = false;
                }

                $scope.isElectron = navigator.userAgent.indexOf("Electron") != -1
                    && (ParametrosS4C.parametros.multivisConfig &&
                        ParametrosS4C.parametros.multivisConfig.length > 0);

                $scope.cancelledArray = [];
                /**
                 * @method stopShare
                 * @param {*} divId
                 * @param {*} closeAllShare
                 */                  
                $scope.stopShare = function (divId, closeAllShare) {

                    if (closeAllShare) {
                        for (var index in $scope.renderes[divId]) {
                            $scope.renderes[divId][index].closeApp($scope.renderes[divId][index]);
                        }
                        return;
                    }

                    if (ParametrosS4C.parametros.multivisConfig.length == 0) {
                        return;
                    }

                    if (ParametrosS4C.parametros.multivisConfig.length == 1) {

                        if ($scope.renderes[divId] &&
                            $scope.renderes[divId][ParametrosS4C.parametros.multivisConfig[0].hostname]) {
                            $scope.renderes[divId][ParametrosS4C.parametros.multivisConfig[0].hostname].closeApp($scope.renderes[divId][ParametrosS4C.parametros.multivisConfig[0].hostname]);
                            $scope.renderes[divId][ParametrosS4C.parametros.multivisConfig[0].hostname] = null;
                        }

                        showShare(divId);
                        return;
                    }

                    var confirm = $mdDialog.confirm({
                        locals: { renderes: $scope.renderes },
                        templateUrl: 'app/directives/preset/escolhaMultivis.html',
                        controller: function ($scope, $mdDialog, renderes) {

                            $scope.res = $scope.$root.res;
                            $scope.multivisSelecionado;
                            $scope.multivisList = ParametrosS4C.parametros.multivisConfig;

                            $scope.rendered = false;
                            var interval = $interval(function () {
                                if (!$scope.rendered && document.getElementById("escolhaMultivis")) {
                                    document.getElementById("escolhaMultivis").style.top = window.positionY + "px";
                                    if (window.positionX - 400 > 0) {
                                        document.getElementById("escolhaMultivis").style.left = (window.positionX - 400) + "px";
                                    } else {
                                        document.getElementById("escolhaMultivis").style.left = window.positionX + "px";
                                    }
                                    $scope.rendered = true;
                                    $interval.cancel(interval);
                                }
                            }, 30);

                            $scope.ok = function () {

                                if (!$scope.multivisSelecionado) {
                                    return;
                                }

                                if (renderes[divId] && renderes[divId][$scope.multivisSelecionado.hostname]) {
                                    renderes[divId][$scope.multivisSelecionado.hostname].closeApp(renderes[divId][$scope.multivisSelecionado.hostname]);
                                    renderes[divId][$scope.multivisSelecionado.hostname] = null;
                                }

                                showShare(divId);
                                $mdDialog.hide();
                            }

                            $scope.cancelar = function () {
                                $mdDialog.hide();
                            };
                        },
                        parent: angular.element(document.body)
                    });

                    $mdDialog.show(confirm).then(function () { }, function () { });
                }

                /**
                 * @method sendCamera
                 * @param {*} endereco
                 */                 
                $scope.sendCamera = function (endereco) {

                    var confirm = $mdDialog.confirm({
                        locals: {},
                        templateUrl: 'app/directives/preset/escolhaMultivis.html',
                        controller: function ($scope, $mdDialog) {

                            $scope.res = $scope.$root.res;
                            $scope.multivisSelecionado;
                            $scope.multivisList = ParametrosS4C.parametros.multivisConfig;

                            $scope.rendered = false;
                            var interval = $interval(function () {
                                if (!$scope.rendered && document.getElementById("escolhaMultivis")) {
                                    document.getElementById("escolhaMultivis").style.top = window.positionY + "px";
                                    document.getElementById("escolhaMultivis").style.left = (window.positionX - 400) + "px";
                                    $scope.rendered = true;
                                    $interval.cancel(interval);
                                }
                            }, 30);

                            $scope.ok = function () {

                                if (!$scope.multivisSelecionado) {
                                    return;
                                }

                                var multivis = $scope.multivisSelecionado.hostname;
                                $.ajax({
                                    url: multivis + "/openCamera?rtsp=" + endereco.slice(44, endereco.length),
                                    method: "GET",
                                    success: function (data) {
                                        console.log(data)
                                    },
                                    error: function (data) {
                                        console.log(data);
                                    }
                                });

                                $mdDialog.hide();
                            }

                            $scope.cancelar = function () {
                                $mdDialog.hide();
                            };
                        },
                        parent: angular.element(document.body)
                    });

                    $mdDialog.show(confirm).then(function () { }, function () { });
                }

                /**
                 * @method escolhaModulos
                 * @param {*} item
                 */   
                function escolhaModulos(item) {

                    if ((!MainState.getPermissoes().permissoesEdicao.presetPublico && Preset.config.preset.padrao != true)
                        || (Preset.config.preset.padrao == true && !MainState.getPermissoes().permissoesExtras.alterarPresetAgencia)) {
                        return;
                    }

                    $mdDialog.show({
                        clickOutsideToClose: true,
                        escapeToClose: true,
                        templateUrl: 'app/directives/escolha-modulos/escolha-modulos.html',
                        locals: {
                            modulos: $scope.modulos
                        },
                        controller: function ($scope, $rootScope) {

                            $scope.res = $rootScope.res;
                            $scope.modulosSelecionados = [];

                            loadCategoriesAndApplications();

                            /**
                             * @method loadCategoriesAndApplications
                             */
                            function loadCategoriesAndApplications() {
                                CategoriaAplicacaoService.obter().then(function (categorias) {
                                    $scope.categorias = categorias;
                                    $scope.favoritos = [];

                                    _.each($scope.categorias, function (categoria) {
                                        _.each(categoria.aplicacoes, function (aplicacao) {
                                            _.each(aplicacao.faces, function (face) {

                                                if (aplicacao.nome != 'Fusion') {
                                                    face.icon = aplicacao.urlIcon;
                                                } else if (!MainState.isToShow('fusion_category')) {
                                                    aplicacao.hide = true;
                                                }
                                                if (face.favorito) {
                                                    $scope.favoritos.push(face);
                                                }

                                                if (aplicacao.template) {
                                                    face.template = aplicacao.template;
                                                }
                                            })
                                        })
                                    });

                                    $scope.devicesSelected = {};
                                    $scope.orgaosSelected = [];
                                    $scope.listOrgaos;
                                    $scope.devices;
                                    $scope.isChecked= true;
                                    getDevicesList();
                                    getOrgaosList();
                                    verifyMapModule();
                                    removeEmptyApplication();
                                    $scope.selecionarFavoritos();

                                    /**
                                     * @method toggle
                                     * @param {*} item
                                     */
                                    $scope.toggle = function (item) {
                                         list = $scope.orgaosSelected
                                        var idx = list.indexOf(item);
                                        if (idx > -1) {
                                            list.splice(idx, 1);
                                        }
                                        else {
                                            list.push(item);
                                        }
                                    };

                                    /**
                                     * @method exists
                                     */
                                    $scope.exists = function (item) {
                                        list = $scope.orgaosSelected
                                        return list.indexOf(item) > -1;
                                    };

                                    if (isChrome()) {
                                        removeRdpMultivisAndWebview($scope);
                                    }
                                });
                            }

                            /**
                             * @method removeEmptyApplication
                             */
                            function removeEmptyApplication() {
                                _.each($scope.categorias, function (categoria) {
                                    categoria.aplicacoes = _.filter(categoria.aplicacoes, function (aplicacao) {
                                        return aplicacao.template != 'app/components/modulos/modulo-vazio.html';
                                    });
                                });
                            }

                            /**
                             * @method isChrome
                             */
                            function isChrome() {
                                return navigator.userAgent.indexOf("Electron") == -1;
                            }

                            /**
                             * @method removeRdpMultivisAndWebview
                             * @param {*} $scope 
                             */
                            function removeRdpMultivisAndWebview($scope) {
                                _.each($scope.categorias, function (categoria) {
                                    categoria.aplicacoes = _.filter(categoria.aplicacoes, function (aplicacao) {
                                        return aplicacao.template != 'app/components/modulos/modulo-rdp.html' &&
                                            aplicacao.template != 'app/components/modulos/modulo-multivis.html' &&
                                            aplicacao.template != 'app/components/modulos/modulo-webview.html';
                                    });
                                });
                            }

                            /**
                             * @method getDevicesList
                             */
                            function getDevicesList() {
                                HdmiService.getDevicesList().then(function (devices) {
                                    $scope.devices = _.cloneDeep(devices);
                                    buildDevicesNames();
                                });
                            }

                            /**
                             * @method getOrgaosList
                             */
                            function getOrgaosList() {
                                $http.get(API_ENDPOINT + 'relatorio/orgaos').then(function (orgaos) {
                                        if (typeof orgaos.data === 'object') {
                                            console.log(JSON.stringify(orgaos.data));
                                            $scope.listOrgaos = orgaos.data;
                                        } else {
                                            console.log("Erro na consulta");
                                        }
                                    }, function (err) {
                                        console.log(err);
                                    });
                            }


                            /**
                             * @method buildDevicesNames
                             */
                            function buildDevicesNames() {
                                var videoIndex = 1;
                                var audioInputIndex = 1;
                                var audioOutputIndex = 1;

                                for (var index in $scope.devices) {
                                    var kind = $scope.devices[index].kind;
                                    if (kind == 'videoinput') {
                                        $scope.devices[index].name = videoIndex + '\xa0\xa0\xa0' + $scope.devices[index].label;
                                        videoIndex++;
                                    }

                                    if (kind == 'audioinput') {
                                        $scope.devices[index].name = audioInputIndex + '\xa0\xa0\xa0' + $scope.devices[index].label;
                                        audioInputIndex++;
                                    }

                                    if (kind == 'audiooutput') {
                                        $scope.devices[index].name = audioOutputIndex + '\xa0\xa0\xa0' + $scope.devices[index].label;
                                        audioOutputIndex++;
                                    }
                                }
                            }

                            /**
                             * @method favoritar
                             * @param {*} face
                             */
                            $scope.favoritar = function (face) {

                                if (face.favorito == null || face.favorito == undefined) {
                                    face.favorito = false;
                                }
                                face.favorito = !face.favorito;

                                FaceService.atualizar(face).then(function () {
                                    if (!face.favorito) {
                                        $scope.favoritos = _.filter($scope.favoritos, function (f) {
                                            return f.id != face.id;
                                        });
                                    } else {
                                        $scope.favoritos.push(face);
                                    }

                                    $scope.selecionarFavoritos();
                                    $scope.hideMenus();
                                });
                            }

                            /**
                             * @method hideMenus
                             */
                            $scope.hideMenus = function () {
                                if (lastId) {
                                    $('#' + lastId).css('display', 'none');
                                }
                            }

                            var lastId;
                            /**
                             * @method showContextMenu
                             * @param {*} id
                             */
                            $scope.showContextMenu = function (id) {

                                if (lastId) {
                                    $('#' + lastId).css('display', 'none');
                                }
                                $('#' + id).css('display', 'block');
                                lastId = id;
                            }

                            /**
                             * @method excluirFace
                             * @param {*} face
                             */
                            $scope.excluirFace = function (face) {

                                vModal('modalId', $scope.res('COMUM_ATENCAO'),
                                    '<h6>' + $scope.res('COMUM_MENSAGEMCONFIRMACAODELETAR') + '?</h6>' +
                                    '<div class="modal-footer p-1 pt-2 border-0">' +
                                    '<button md-theme="default" class="btn btn-secondary" btn="close-modal" ng-click="fecharModal()">'
                                    + $scope.res('COMUM_CANCELAR') + '</button>' +
                                    '<button type="button" class="btn btn-secondary" btn="deletar-aplicativo" ng-click="deletarAplicativo()">'
                                    + $scope.res('COMUM_CONFIRMAR') + '</button></div>', function () {
                                    }, true);

                                $('[btn=close-modal]').on('click', function () {
                                    $scope.fecharModal()
                                });
                                $('[btn=deletar-aplicativo]').on('click', function () {
                                    $scope.deletarAplicativo(face)
                                });

                                $scope.hideMenus();
                            }

                            /**
                             * @method mostraBarra
                             */
                            $scope.mostrarBarra = function () {
                                $('.face').each(function() {
                                     if (!$(this).find('.barraModulo').hasClass('mostraBarra')) {
                                         $(this).find('.wrapper').addClass('topClass');
                                     }
                                })
                            }

                            /**
                             * @method fecharModal
                             */
                            $scope.fecharModal = function () {
                                $('#modalId').remove();
                                $('#outsideId').remove();
                            }

                            /**
                             * @method deletarAplicativo
                             */
                            $scope.deletarAplicativo = function (face) {
                                _.each(Preset.config.preset.PresetModulos, function (modulo) {
                                    if (modulo.Face && modulo.Face.id == face.id) {
                                        Preset.removerItem(modulo);
                                        Preset.config.preset.PresetModulos.splice(Preset.config.preset.PresetModulos.indexOf(modulo), 1);
                                    }
                                })

                                FaceService.remover(face).then(function () {
                                    $scope.favoritos.splice($scope.favoritos.indexOf(face), 1);
                                    $scope.modulosSelecionados.splice($scope.modulosSelecionados.indexOf(face), 1);
                                    $scope.favoritos.splice($scope.favoritos.indexOf(face), 1);
                                });
                                $scope.fecharModal();
                            }

                            $scope.rendered = false;
                            var interval = $interval(function () {
                                if (!$scope.rendered && document.getElementById("escolhaModulos")) {

                                    $scope.rendered = true;
                                    var offsetX = $(window).width() / 4 - 500;
                                    var offsetY = $(window).height() / 4 + 250;
                                    if ($(window).width() > 1920) {
                                        if (window.positionX < $(window).width() / 2) {
                                            document.getElementById("escolhaModulos").style.left = offsetX + "px";
                                        } else {
                                            document.getElementById("escolhaModulos").style.left = ($(window).width() / 2 + offsetX) + "px";
                                        }
                                    }

                                    if ($(window).height() > 2160) {
                                        if (window.positionY < $(window).height() / 2) {
                                            document.getElementById("escolhaModulos").style.top = offsetY + "px";
                                        } else {
                                            document.getElementById("escolhaModulos").style.top = ($(window).height() / 2 + offsetY) + "px";
                                        }
                                    }

                                    $interval.cancel(interval);
                                    $('#escolhaModulos').draggable({ handle: ".card-header", containment: ".ng-scope" });
                                }
                            }, 30);

                            /**
                             * @method selecionarFavoritos
                             */
                            $scope.selecionarFavoritos = function () {
                                $scope.isAdding = false;
                                $scope.isEditing = false;
                                $scope.modulosSelecionados = $scope.favoritos;
                                $scope.aplicacao = { nome: 'FAVORITOS' };
                                $scope.aplicacao.faces = $scope.favoritos;
                            }

                            /**
                             * @method selecionarAplicacao
                             */
                            $scope.selecionarAplicacao = function (aplicacao) {
                                $scope.aplicacao = aplicacao;
                                $scope.modulosSelecionados = aplicacao.faces;
                                $scope.isAdding = false;
                                $scope.isEditing = false;

                                if ($scope.aplicacao.template) {
                                    _.each($scope.aplicacao.faces, function (face) {
                                        face.template = $scope.aplicacao.template;
                                    });
                                }


                            }

                            $scope.textoBusca;
                            $scope.categoriasSelecionadas = $scope.categorias;
                            var aplicacaoNome;
                            /**
                             * @method executeSearch
                             */
                            $scope.executeSearch = function () {

                                $scope.isAdding = false;
                                $scope.isEditing = false;

                                $scope.modulosSelecionados = [];
                                aplicacaoNome = !aplicacaoNome ? $scope.aplicacao.nome : aplicacaoNome;
                                $scope.aplicacao.nome = '';
                                if (!$scope.textoBusca || $scope.textoBusca.length == 0) {
                                    $scope.modulosSelecionados = $scope.aplicacao ? $scope.aplicacao.faces : [];
                                    $scope.aplicacao.nome = aplicacaoNome;
                                    aplicacaoNome = null;
                                    return;
                                }

                                _.each($scope.categorias, function (categoria) {
                                    _.each(categoria.aplicacoes, function (aplicacao) {
                                        _.each(aplicacao.faces, function (face) {

                                            var faceName = $scope.res(face.name);
                                            if (faceName.toLowerCase().indexOf($scope.textoBusca.toLowerCase()) != -1) {
                                                $scope.modulosSelecionados.push(face);
                                            }
                                        })
                                    })
                                })
                            }

                            /**
                             * @method verifyMapModule
                             */
                            function verifyMapModule() {

                                var modulosPreviamenteSelecionados = _.filter(_.map(Preset.config.preset.PresetModulos, function (mod) {
                                    if (mod.Face) {
                                        return mod.Face.name;
                                    }
                                    return mod.name;
                                }), function (mod) { return mod != undefined });

                                modulosPreviamenteSelecionados = _.union(modulosPreviamenteSelecionados, Preset.config.preset.PresetModulos.novasFaces);

                                var hasMap = existsModule(modulosPreviamenteSelecionados, 'MODULO_MAPA');
                                var hasDetalhamento = existsModule(modulosPreviamenteSelecionados, 'MODULO_DETALHAMENTO');

                                if (hasMap) {
                                    hideModule('MODULO_MAPA');
                                }

                                if (hasDetalhamento) {
                                    hideModule('MODULO_DETALHAMENTO');
                                }
                            }

                            /**
                             * @method existsModule
                             * @param {*} modules 
                             * @param {*} moduleName 
                             */
                            function existsModule(modules, moduleName) {
                                var exists = false;
                                angular.forEach(modules, function (mod) {

                                    if (mod == moduleName || mod == $scope.res(moduleName)) {
                                        exists = true;
                                    }
                                });
                                return exists;
                            }

                            /**
                             * @method hideModule
                             * @param {*} moduleName 
                             */
                            function hideModule(moduleName) {
                                _.each($scope.categorias, function (categoria) {
                                    _.each(categoria.aplicacoes, function (aplicacao) {
                                        _.each(aplicacao.faces, function (face) {
                                            if (face && face.name == moduleName) {
                                                aplicacao.faces = _.filter(aplicacao.faces, function (f) {
                                                    return f.name != moduleName
                                                });
                                                $scope.favoritos = _.filter($scope.favoritos, function (f) {
                                                    return f.name != moduleName
                                                });
                                            }
                                        })
                                    })
                                })
                            }

                            $scope.isAdding = false;
                            $scope.face = {};
                            /**
                             * @method novaInstancia
                             */
                            $scope.novaInstancia = function () {
                                $scope.isAdding = true;
                                $scope.face.extras = [];
                                $scope.face.name = '';
                                _.each($scope.aplicacao.extras, function (extra) {
                                    $scope.face.extras.push({ nome: extra.rotulo, valor: '', tipo: extra.tipo });
                                });

                                setFileNameInInputLabel();
                            }

                            /**
                             * @method setFileNameInInputLabel
                             */
                            function setFileNameInInputLabel() {
                                setTimeout(function () {
                                    $('#inputArquivo').on('change', function (e) {
                                        let fileName = e.target.files[0].name;
                                        $('#labelArquivo').html('');
                                        $('#labelArquivo').append(fileName);
                                    });
                                }, 200);
                            }

                            $scope.isEditing = false;
                            /**
                             * @method editarFace
                             */
                            $scope.editarFace = function (face) {
                                $scope.isEditing = true;
                                $scope.face = face;

                                if ($scope.face.name && $scope.face.extras!= null && $scope.face.extras.length > 0 && $scope.face.extras[0].tipo == 'arquivo-chart') {
                                    console.log($scope.face.extras[0].orgaos);
                                    console.log($scope.listOrgaos)

                                    $scope.face.extras[0].orgaos.forEach(element => {
                                        var item = _.find($scope.listOrgaos, function (orgao) {
                                           return orgao.codigo == element;
                                       });
                                       item.checked = true;
                                   });
                                }

                                if (isHdmiApplication($scope.face.extras)) {
                                    setSelectedDevices();
                                }

                                setTimeout(function () {

                                    $('#labelArquivo').html('');
                                    $('#labelArquivo').append(face.extras.fileName);

                                    $('#inputArquivo').on('change', function (e) {
                                        let fileName = e.target.files[0].name;
                                        $('#labelArquivo').html('');
                                        $('#labelArquivo').append(fileName);
                                    });
                                }, 200);

                                $scope.hideMenus();
                            }

                            function setSelectedOrgaos() {

                            }

                            /**
                             * @method setSelectedDevices
                             */
                            function setSelectedDevices() {

                                if (!$scope.devicesSelected) {
                                    return;
                                }

                                $scope.devicesSelected.videoinput = _.find($scope.devices, function (device) {
                                    return $scope.face.extras[0].devices.videoinput.deviceId == device.deviceId && device.kind == 'videoinput';
                                });

                                $scope.devicesSelected.audioinput = _.find($scope.devices, function (device) {
                                    return $scope.face.extras[0].devices.audioinput.deviceId == device.deviceId && device.kind == 'audioinput';
                                });

                                $scope.devicesSelected.audiooutput = _.find($scope.devices, function (device) {
                                    return $scope.face.extras[0].devices.audiooutput.deviceId == device.deviceId && device.kind == 'audiooutput';
                                });
                            }

                            function ext(filename) {
                                var index = _.lastIndexOf(filename, '.');
                                return filename.substring(index, filename.length);
                            }

                            $scope.fileId;
                            var uploader = $scope.uploader = new FileUploader(),
                                uploadCallbackQueue = [];

                            $scope.uploader.filters.push({
                                'name': 'enforceMaxFileSize',
                                'fn': function (item, evt) {
                                    var megaByte = parseInt(item.size / 1000000) + "MB";
                                    if (item.size <= 26214400) {
                                        return item.size <= 26214400
                                    } else {
                                        var msgFileExceeded = localize.getLocalizedString('COMUM_TAMANHOFILEULTRAPASSADO');
                                        var msgFileLimit = localize.getLocalizedString('COMUM_FILELIMIT');
                                        $mdDialog
                                            .show($mdDialog.alert()
                                                .title(msgFileExceeded)
                                                .content(msgFileLimit + megaByte)
                                                .ok('OK'))
                                        return item.size <= 26214400
                                    }
                                }
                            });

                            /**
                             * @method salvarArquivo
                             */
                            function salvarArquivo() {

                                if ($scope.face.extras[0] && $scope.face.extras[0].tipo == 'arquivo-imagem') {
                                    uploader.url = '/filemanager/addarquivo/FULL_IMAGE';
                                } else if ($scope.face.extras[0] && $scope.face.extras[0].tipo == 'arquivo-video') {
                                    uploader.url = '/filemanager/addarquivo/VIDEO';
                                } else {
                                    uploader.url = '/filemanager/addarquivo/OTHER';
                                }

                                uploader.uploadAll();
                            }

                            $scope.uploader.alias = 'arquivo';
                            $scope.uploader.removeAfterUpload = true;
                            $scope.uploader.onCompleteItem = function (fileItem, response, status, headers) {
                                salvarFace(response);
                            };

                            $scope.uploader.onAfterAddingFile = function (item, evt, arquivo) {
                                item.novoNome = item.file.name;
                            }

                            $scope.uploader.onBeforeUploadItem = function (item) {

                                item.url = uploader.url;
                                var token = window.sessionStorage.getItem('s4cToken');
                                var tokenObj = JSON.parse(token);
                                item.headers = {
                                    'Authorization': 'Bearer ' + tokenObj.access_token
                                };
                                item.file.name = item.novoNome + ext(item.file.name);
                            };

                            $scope.uploader.onErrorItem = function (fileItem, response, status, headers) {
                                console.info('onErrorItem', fileItem, response, status, headers);
                            };

                            $scope.uploader.onProgressItem = function (fileItem, progress) {
                                console.info('onProgressItem', fileItem, progress);
                            };
                            $scope.uploader.onCompleteAll = function () {

                                _.each(uploadCallbackQueue, function (callback) {
                                    callback();
                                });
                            };

                            /**
                             * @method isHdmiApplication
                             * @param {*} extras 
                             */
                            function isHdmiApplication(extras) {
                                return extras && extras.length > 0 && extras[0].tipo == 'hdmi';
                            }

                            /**
                             * @method isChartApplication
                             */
                            function isChartApplication(){
                                return $scope.face.name && $scope.face.extras != null && $scope.face.extras.length > 0 && $scope.face.extras[0].tipo == 'arquivo-chart';
                            }
                            /**
                             * @method salvar
                             */
                            $scope.salvar = function () {

                                if (isChartApplication()) {
                                	$scope.face.extras[0].orgaos = _.map(_.filter($scope.listOrgaos, function (orgaoFilter) {
                                		return orgaoFilter.checked != undefined && orgaoFilter.checked == true;
                                    }), function (orgaoMap) { return orgaoMap.codigo; });

                                    salvarFace();
                                    return;
                                }

                                if (!$scope.face.name || (!$scope.face.endereco && (!$scope.face.extras || ($scope.face.extras.length > 0 &&
                                    $scope.face.extras[0].tipo != 'arquivo-imagem' &&
                                    $scope.face.extras[0].tipo != 'arquivo-video' &&
                                    $scope.face.extras[0].tipo != 'arquivo-pdf' &&
                                    $scope.face.extras[0].tipo != 'hdmi')))) {
                                    return;
                                }

                                if (isHdmiApplication($scope.face.extras)) {
                                    $scope.face.extras[0].devices = $scope.devicesSelected;

                                    if (!$scope.face.extras[0].devices.videoinput
                                        || !$scope.face.extras[0].devices.audioinput
                                        || !$scope.face.extras[0].devices.audiooutput) {
                                        return;
                                    }
                                }

                                if ($scope.face.extras.length == 0 || ($scope.face.extras.length > 0 &&
                                    $scope.face.extras[0].tipo != 'arquivo-imagem' &&
                                    $scope.face.extras[0].tipo != 'arquivo-video' &&
                                    $scope.face.extras[0].tipo != 'arquivo-pdf')) {
                                    salvarFace();
                                    return;
                                }

                                if ($scope.face.extras[0].fileId) {
                                    FileService.deleteFile($scope.face.extras[0].fileId).then(function () {
                                        salvarArquivo();
                                    });
                                } else {
                                    salvarArquivo();
                                }
                            }

                            /**
                             * @method salvarFace
                             * @param {*} fileInfo 
                             */
                            function salvarFace(fileInfo) {

                                if (fileInfo) {
                                    $scope.face.extras[0].fileName = fileInfo.fileName;
                                    $scope.face.extras[0].fileId = fileInfo.fileId;
                                    $scope.face.extras[0].filePath = 'uploads/' + fileInfo.filePath;
                                    $scope.face.endereco = '';
                                }

                                if ($scope.isAdding) {
                                    addFace();
                                } else {
                                    editFace();
                                }
                            }

                            /**
                             * @method editFace
                             */
                            function editFace() {
                                var objeto = {};
                                objeto.id = $scope.face.id;
                                objeto.name = $scope.face.name;
                                objeto.endereco = $scope.face.endereco;
                                objeto.extras = $scope.face.extras;
                                objeto.favorito = $scope.face.favorito;

                                var modulos = _.filter(Preset.config.preset.PresetModulos, function (mod) {
                                    return mod.Face != null && mod.Face.id == $scope.face.id;
                                });

                                if(modulos != null && modulos.length > 0){
                                	modulos[0].Face.extras[0].orgaos = $scope.face.extras[0].orgaos;
                                }

                                FaceService.atualizar(objeto).then(function (face) {
                                    $scope.face = {};
                                    $scope.devicesSelected = {};
                                    $scope.isEditing = false;
                                });
                            }

                            /**
                             * @method addFace
                             */
                            function addFace() {
                                $scope.face.tipo = 'INSTANCIA';
                                $scope.face.aplicacao = { id: $scope.aplicacao.id };
                                $scope.face.favorito = false;
                                $scope.face.template = $scope.aplicacao.template;

                                FaceService.salvar($scope.face).then(function (face) {
                                    face.template = $scope.aplicacao.template;
                                    face.icon = $scope.aplicacao.urlIcon;
                                    $scope.aplicacao.faces.push(face);
                                    $scope.face = {};
                                    $scope.devicesSelected = {};
                                    $scope.isAdding = false;
                                });
                            }

                            /**
                             * @method cancelar
                             */
                            $scope.cancelar = function () {
                                $scope.isAdding = false;
                                $scope.isEditing = false;
                                $scope.face = {};
                                $scope.devicesSelected = {};
                            }

                            /**
                             * @method escolherInstancia
                             */
                            $scope.escolherInstancia = function (instancia) {
                                const escolherInstanciaFinal = new Promise((resolve)=>{
                                    item.FaceId = instancia.id;
                                    item.template = instancia.template;
                                    item.closed = false;
                                    item.name = instancia.name;
                                    item.Face = instancia;

                                    if (Preset.config.preset.PresetModulos.novasFaces === undefined) {
                                        Preset.config.preset.PresetModulos.novasFaces = [];
                                    }

                                    Preset.config.preset.PresetModulos.novasFaces.push(instancia.name);
                                    $mdDialog.hide();
                                    Preset.salvar();
                                    setTimeout(()=>{resolve()},200)
                                });
                                escolherInstanciaFinal.then(()=>$scope.mostrarBarra())
                            }
                        }
                    });
                }
            }
        }
    }
}());