Source: services/MainState.js

    /**
     * @ngdoc service
     * @name MainState
     * @module s4c.services.MainState
     * 
     * @description  Componente para acesso a api do backend e/ou comunicação entre controllers
     * 
     *
     */

     
(function () {
    'use strict';

    MainState.$inject = ['$rootScope', 'CommService', '$interval', '$mdDialog', 'AuthService', 'GRIDSTER_OPTIONS_EDICAO', 'FileReaderService'];

   /**	
	* @method MainState
	* @param {*} $rootScope
	* @param {*} $interval
	* @param {*} $mdDialog
	* @param {*} CommService
	* @param {*} AuthService
	* @param {*} GRIDSTER_OPTIONS_EDICAO
	* @param {*} FileReaderService
	*/
    function MainState($rootScope, CommService, $interval, $mdDialog, AuthService, GRIDSTER_OPTIONS_EDICAO, FileReaderService) {

        var res = $rootScope.res;
        var version = 'Y19W18';

  	   /**	
		* @method getVersion
		*/
        function getVersion() {
            return version;
        }

        var isElectron = navigator.userAgent.indexOf("Electron") != -1

        var ipcRenderer;
        if (isElectron) {
            ipcRenderer = require('electron').ipcRenderer;
        }

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

            if (isElectron) {

                return new Promise(resolve => {
                    ipcRenderer.send('getIp', '');
                    ipcRenderer.on('returnIp', (event, result) => {
                        resolve(' - Ip: ' + result);
                    })
                });
            }

            return new Promise(resolve => {
                resolve('');
            });
        }

        getIp().then(function (result) {
            version = version + result;
        });

  		/**	
		* @method getConfigFile
		*/
        function getConfigFile() {
            return new Promise(resolve => {
                ipcRenderer.send('getConfigFile', '');
                ipcRenderer.on('returnFile', (event, file) => {
                    resolve(file);
                })
            });
        }

  		/**	
		* @method cleanCache
		*/
        function cleanCache() {
            return new Promise(resolve => {
                ipcRenderer.send('cleanCache', '');
                ipcRenderer.on('returnOk', (event, ok) => {
                    ipcRenderer.send('commandExec', 'update_cockpit');
                })
            });
        }

  		/**	
		* @method setConfigFile
		* @param {*} file
		*/
        function setConfigFile(file) {
            return new Promise(resolve => {
                ipcRenderer.send('setConfigFile', file);
                ipcRenderer.on('returnOk', (event, ok) => {
                    resolve(ok);
                })
            });
        }

        var permissoes = {};
        function setPermissoes(perms) {
            permissoes = perms;
        }

  		/**	
		* @method getPermissoes
		*/
        function getPermissoes() {
            return permissoes;
        }

        var directives = {};
        var managers = {};

        // Monitoramento do keep alive *********************************
        var lastMessage;
        var lastMoment = moment();
        var dialog;
        var hasError = false;
        var lastLevel;
        var errorMessage = '';
        var serverOffline = false;

  		/**	
		* @method $interval
		*/
        $interval(function () {

            var now = moment();

            if (lastMessage == 'ok' && serverOffline) {

                serverOffline = false;
                if (dialog) {
                    dialog = undefined;
                }

                var okDialog = $mdDialog.confirm()
                    .title(res('COMUM_ATENCAO'))
                    .content(res('SERVIDOR_VOLTOU'))
                    .ok(res('COMUM_SIM'))
                    .cancel(res('COMUM_NAO'));

                $mdDialog.show(okDialog)
                    .then(function () {
                        location.reload();
                    }, function () {
                        $mdDialog.hide();
                    });

                return;

            } else if (lastMessage == 'ok' && hasError) {
                hasError = false;
            }

            if (dialog) {
                return;
            }

            if ((now.valueOf() - lastMoment.valueOf()) > 120000 && AuthService.user.info != null && AuthService.user.info.showServerOff == 'true') {

                lastMessage = 'nok';
                dialog = true;

                $mdDialog
                    .show({
                        template: '<md-dialog aria-label="' + res('USUARIO_NOVO') + '" class="dialog-resetar-senha"><md-content><h3>' +
                            res('COMUM_ATENCAO') + '</h3><h4>' + res('SERVIDOR_CAIU') + '</h4></md-content></md-dialog>',
                        clickOutsideToClose: false
                    }).then(function () {
                        dialog = undefined;
                        $mdDialog.hide();
                    });

                serverOffline = true;
                return;
            }

            if (lastMessage == 'mobileOff') {

                errorMessage = res('SERVICO_OFFLINE') + " (Cod.:01)";

                hasError = true;
                return;
            }

            if (lastMessage == 'serviceMixOff') {

                errorMessage = res('SERVICO_OFFLINE') + " (Cod.:02)";

                hasError = true;
                return;
            }

            if (lastMessage == 'solrOff') {

                errorMessage = res('SERVICO_OFFLINE') + " (Cod.:03)";

                hasError = true;
                return;
            }

        }, 61000);

  		/**	
		* @method noError
		*/
        function noError() {
            return !hasError;
        }

  		/**	
		* @method getErrorMessage
		*/
        function getErrorMessage() {
            return errorMessage;
        }

        CommService.on('keepAlive', function (result) {
            lastMoment = moment();
            lastMessage = result.info;
            lastLevel = result.level;
        });
        //**************************************************************

  	   /**	
		* @method isToShow
		* @param {*} key
		*/
        function isToShow(key) {

            if ($rootScope.blackList == null) {
                return true;
            }

            return $rootScope.blackList.indexOf(key) < 0;
        }

        /*********** Btn menu modulo *************/

  	   /**	
		* @method menuButtonFunction
		*/
        const menuButtonFunction = () => {
            /**Entrar no modulo**/
            $('.face').on('mouseenter', function () {
                let face = $(this);
                let id = $(this).get(0).id;
                var moduloId = id;
                if (face.prop('hoverTimeout')) {
                    face.prop('hoverTimeout', clearTimeout(face.prop('hoverTimeout')));
                }
                face.prop('hoverIntent', setTimeout(function () {
                    if ($('#' + id + ' .barraModulo').hasClass('mostraBarra')) {
                        return;
                    }
                    $('#' + id + ' .btn-action').addClass('show');
                    $('#' + id).addClass('ativado');
                    menuLimite(id);
                }, 0)); //Tempo para aparecer

                /**Menu Limite**/
                const menuLimite = (id) => {
                    let elementoWidth = $('#' + id).width();
                    let elementoHeight = $('#' + id).height();
                    let menuWidth = $('#' + id + ' .menu-actions').width();
                    let menuHeight = $('#' + id + ' .menu-actions').height() + 47;
                    let pBtn = $('#' + id + " .btn-action").position();
                    if (pBtn && (elementoWidth - menuWidth) <= pBtn.left) {
                        $('#' + id + ' .menu-actions').addClass('menu-actions-invert');
                    } else {
                        $('#' + id + ' .menu-actions').removeClass('menu-actions-invert');
                    };
                    if (pBtn && (elementoHeight - menuHeight) <= pBtn.top) {
                        $('#' + id + ' .menu-actions').addClass('menu-actions-top');
                    } else {
                        $('#' + id + ' .menu-actions').removeClass('menu-actions-top');
                    };
                };
                /**Fim menu limite**/


                /** Mostrar Dropdown **/
                $('.btn-action').unbind("click").click(function (event) {
                    $('#' + id + ' .menu-actions').toggleClass('show');
                    menuLimite(id);
                });

                $('.btn-action:focus').unbind("click").dblclick(function (event) {
                    $(this).next().addClass("mover-modulo-active").addClass("mover-modulo-active")
                });

                $('#' + id + ' .btn-action').mousedown(function () {
                    $(this).removeClass('btn-reset');
                });

                /** Fim mostrar dropdown **/

                /**Mover btn**/
                $('#' + id + ' .btn-action').draggable({
                    containment: "parent",
                    cursor: "crosshair",
                    opacity: 0.35,
                    start: function () {
                        $('#' + id + ' .mover-modulo').addClass("show");
                    },
                    drag: function () {
                        if ($('#' + id + ' .menu-actions').hasClass('show')) {
                            menuLimite(id);
                        }
                    },
                    stop: function () {
                        $('#' + id + ' .mover-modulo').removeClass("show");
                        $('#' + id + ' .menu-actions').toggleClass('show');
                    }
                });
                /**Fim Mover btn**/

                /**Mover Modulo**/
                $('[data-action-mover]').unbind("click").on('click', function () {
                    $('#' + id + ' [data-mover-modulo]').addClass("mover-modulo-active");
                    $('#' + id + ' [data-mover-modulo]').addClass("show");
                });

                $('#' + id + ' [data-mover-modulo]').mouseup(function () {
                    $('#' + id + ' [data-mover-modulo]').removeClass("mover-modulo-active");
                    $('#' + id + ' [data-mover-modulo]').removeClass("show");
                });

                /**Fim mover modulo**/


                /**Toolbar*/
                $('[data-action-toolbox]').unbind("click").on('click', function () {
                    $('#' + id + ' .barraModulo').addClass('mostraBarra');
                    $('#' + id + ' .barraModulo').css('position', 'absolute');
                    $('#' + id + ' .barraModulo .md-toolbar-tools span').addClass('menuFonte');
                    $('#' + id + ' .btn-action').removeClass('show');
                    $('#' + id + ' .wrapper').removeClass('topClass');
                    $('.barra-mapa-top').addClass('top-show');
                    $('.wrapper').addClass('top-show-map');
                    if ($('#' + id + ' .menuBar div').hasClass('webViewNav')) {
                        $('#' + id + ' .wrapper').addClass('mt-5');
                    }
                });
                /**Fim toolbar**/
            });
            /**Fim Entrar no modulo**/

            /**Sair do modulo**/
            $('.face').on('mouseleave', function () {
                let face = $(this);
                let id = $(this).get(0).id;
                if (face.prop('hoverIntent')) {
                    face.prop('hoverIntent', clearTimeout(face.prop('hoverIntent')));
                }
                face.prop('hoverTimeout', setTimeout(function () {
                    $('#' + id + ' .btn-action').removeClass('show');
                    $(this).removeClass("mover-modulo-active");
                }, 0)); //Tempo para ocultar
            });
            /**Fim Sair no modulo**/

            $('[data-modal=show]').unbind("click").on('click', function () {
                alert('Teste');
            });

        }

  	   /**	
		* @method btnModuloReset
		* @param {*} itemOptions
		* @param {*} event
		*/
        const btnModuloReset = (event, itemOptions) => {

            if(!itemOptions){
                return;
            }
            let idModulo = itemOptions.id
            let mouseX = event.pageX
            let mouseY = event.pageY

            if (!($('#' + idModulo).find('.barraModulo').hasClass('mostraBarra')) & $('#' + idModulo).hasClass('face')) {
                var btnModulo
                if (!($('#' + idModulo).find('.btn-action').hasClass('show'))) {
                    btnModulo = $('#' + idModulo).find('.btn-action').addClass('show')
                } else {
                    btnModulo = $('#' + idModulo).find('.btn-action')
                }
                if (btnModulo.offset().left >= mouseX | btnModulo.offset().top >= mouseY) {
                    btnModulo.animate({
                        top: 20,
                        left: 20
                    }, 1200);
                }
            }

            if ($('#legendaContainer').hasClass('show')) {

                let legenda = $('#legendaContainer')

                if (legenda.offset().left >= mouseX | legenda.offset().top >= mouseY) {
                    legenda.animate({
                        top: 60,
                        left: 20
                    }, 1200);
                }
            }
        }
        /*********** Fim Btn menu modulo *************/

  	   /**	
		* @method reboot
		* @param {*} toLogout
		* @param {*} logout
		*/
        function reboot(toLogout, logout) {

            var confirm = $mdDialog.confirm()
                .title(res('CERTEZA_REINICIAR'))
                .ok(res('COMUM_SIM'))
                .cancel(res('COMUM_NAO'));

            $mdDialog.show(confirm).then(function () {
                if (toLogout) {
                    logout();
                }
                cleanCache();
                ipcRenderer.send('commandExec', 'reiniciar');
            });
        }

  	   /**	
		* @method updateCockpit
		* @param {*} logout
		*/
        function updateCockpit(logout) {
            logout();
            cleanCache();
            ipcRenderer.send('commandExec', 'update_cockpit');
        }

  	   /**	
		* @method shutdown
		* @param {*} toLogout
		* @param {*} logout
		*/
        function shutdown(toLogout, logout) {

            var confirm = $mdDialog.confirm()
                .title(res('CERTEZA_DESLIGAR'))
                .ok(res('COMUM_SIM'))
                .cancel(res('COMUM_NAO'));

            $mdDialog.show(confirm).then(function () {
                if (toLogout) {
                    logout();
                }
                ipcRenderer.send('commandExec', 'desligar');
            });
        }

        var rowsCols = {};

  	   /**	
		* @method getGridRowsCols
		*/
        function getGridRowsCols(){
            return rowsCols;
        }

  	   /**	
		* @method loadGridsterOptions
		* @param {*} funcao
		*/
        function loadGridsterOptions(funcao){
            FileReaderService.readTextFile("/s4c_dir/gridster.json", function (text) {
                var data = JSON.parse(text);
                GRIDSTER_OPTIONS_EDICAO.columns = data.colunas;
                GRIDSTER_OPTIONS_EDICAO.maxColumns = data.colunas;
                GRIDSTER_OPTIONS_EDICAO.maxRows = data.linhas;
                GRIDSTER_OPTIONS_EDICAO.colWidth = parseInt((($(window).width() - 5) / GRIDSTER_OPTIONS_EDICAO.columns).toFixed(), 10);
                var electron = navigator.userAgent.indexOf("Electron") != -1;
                if (!electron) {
                    GRIDSTER_OPTIONS_EDICAO.rowHeight = parseInt((($(window).height() + 0) / GRIDSTER_OPTIONS_EDICAO.maxRows).toFixed() - 9, 10);
                } else {
                    GRIDSTER_OPTIONS_EDICAO.rowHeight = parseInt((($(window).height() + 0) / GRIDSTER_OPTIONS_EDICAO.maxRows).toFixed(), 10);
                }

                rowsCols = {rows: data.linhas, cols: data.colunas};
                if(funcao){
                    funcao();
                }
            });
        }

        return {
            detalhamentosAtivos: {},
            // Managers
            managers: managers,
            directives: directives,
            registerManager: registerManager,
            getManager: getManager,
            unregisterManager: unregisterManager,
            // Directives
            registerDirective: registerDirective,
            getDirective: getDirective,
            unregisterDirective: unregisterDirective,
            getErrorMessage: getErrorMessage,
            noError: noError,
            getVersion: getVersion,
            isToShow: isToShow,
            menuButtonFunction: menuButtonFunction,
            reboot: reboot,
            shutdown: shutdown,
            updateCockpit: updateCockpit,
            getConfigFile: getConfigFile,
            setConfigFile: setConfigFile,
            cleanCache: cleanCache,
            resizeMenuMapa: resizeMenuMapa,
            btnModuloReset:btnModuloReset,
            setPermissoes: setPermissoes,
            getPermissoes: getPermissoes,
            getGridRowsCols: getGridRowsCols,
            loadGridsterOptions: loadGridsterOptions

        };

  	   /**	
		* @method getManager
		* @param {*} name
		*/
        function getManager(name) {
            return managers[name];
        }

  	   /**	
		* @method registerManager
		* @param {*} name
		* @param {*} manager
		*/
        function registerManager(name, manager) {
            managers[name] = manager;
            return managers[name];
        }

  	   /**	
		* @method unregisterManager
		* @param {*} name
		*/
        function unregisterManager(name) {
            delete managers[name];
        }

  	   /**	
		* @method resizeMenuMapa
		*/
        function resizeMenuMapa() {
            var wFace = $('.modulo-mapa').width()
            if (wFace <= 650) {
                $('.buscarFilter').addClass('position-absolute');
                $('.btnMap').hide();
                $('.dropdown-map').show()
            } else {
                $('.btnMap').show();
                $('.buscarFilter').removeClass(' position-absolute');
                $('.dropdown-map').hide()
            }
        }

  	   /**	
		* @method unregisterDirective
		* @param {*} name
		*/
        function unregisterDirective(name) {

            //Nunca remover a diretiva msi.
            if (name == 'msiFilter' || name == 'msi') {
                return;
            }

            if (directives.hasOwnProperty(name)) {
                directives[name].onDestroy();
            }
        }

  	   /**	
		* @method getDirective
		* @param {*} name
		*/
        function getDirective(name) {
            if (directives.hasOwnProperty(name)) {
                return directives[name].api;
            }

            return undefined;
        }

  	   /**	
		* @method registerDirective
		* @param {*} name
		* @param {*} directiveApi
		*/
        function registerDirective(name, directiveApi) {
            if (!directives.hasOwnProperty(name)) {
                directives[name] = {
                    api: directiveApi,
                    onDestroy: function () {
                        delete directives[name];
                    }
                };
            } else {
                directives[name].api = directiveApi;
            }

            return directives[name];
        }

    }

    angular.module('s4c.services.MainState', [])
        .service('MainState', MainState);
})();