Source: managers/DetalhamentoManager.js

/**
 * @ngdoc managers
 * @name DetalhamentoManager
 * @module s4c.managers.DetalhamentoManager
 *
 * @description
 * `DetalhamentoManager` Componente para comunicação entre uma página html qualquer e o controller da diretiva
 * 
 * 
 */
(function () {
    'use strict';

    function DetalhamentoManager(MainState, $q, $mdDialog, MapaService, $timeout, ZonaObservacaoService, ZonaDeObservacaoManager) {
        var subItens = new L.LayerGroup([]);

        return {
            'ativo': false,
            'activeWindow': false,
            'top': 10,
            'right': 10,
            'titulo': 'Detalhamento',
            'data': {},
            'camerasProximas': [],
            'poisProximos': [],
            'incidentesProximos': [],
            'poisAlertados': [],
            'poiCamadas': [],
            'subItens': new L.LayerGroup([]),
            'poiAtivo': -1,
            'managers': [],

            /**
             * @method getPoiCamada
             * @param {*} idCategoria 
             */
            'getPoiCamada': function (idCategoria) {

                var selected;
                angular.forEach(this.poiCamadas, function (cmd) {
                    if (cmd.idCategoria == idCategoria) {
                        selected = cmd;
                    }
                });

                return selected;
            },
            /**
             * @method addPoiCamada
             * @param {*} camada 
             */
            'addPoiCamada': function (camada) {

                var selected;
                angular.forEach(this.poiCamadas, function (cmd) {
                    if (cmd.idCategoria == camada.idCategoria) {
                        selected = cmd;
                    }
                });

                if (!selected) {
                    return;
                }

                this.poiCamadas.push(camada);
            },
            /**
             * @method addPoiAlertado
             * @param {*} poi 
             */
            'addPoiAlertado': function (poi) {
                this.poisAlertados.push(poi);
            },
            /**
             * @method alreadyAdded
             * @param {*} poi 
             */    
            'alreadyAdded': function (poi) {

                var added;
                angular.forEach(this.poisAlertados, function (poiAlterado) {
                    if (poiAlterado.id == poi.id) {
                        added = poiAlterado;
                    }
                });

                return added;

            },
            
            /**
             * @method samePoi
             * @param {*} id
             */
            'samePoi': function (id) {

                if (this.poiAtivo == id) {
                    return true;
                }

                return false;
            },

            /**
             * @method voarParaObjeto
             * @param {*} obj 
             */
            'voarParaObjeto': function (obj) {
                var coords;
                if (typeof obj.geojson === 'string') {
                    coords = JSON.parse(obj.geojson);
                } else {
                    coords = obj.geojson;
                }

                MapaService.flyTo(coords);
            },
            /**
             * @method voarParaSubItem
             * @param {*} data 
             * @param {*} obj 
             */
            'voarParaSubItem': function (data, obj) {
                var coords;

                MainState.managers.HabilitarCamadasManager.habilitarCamadas(obj);

                if (typeof obj.geojson === 'string') {
                    coords = JSON.parse(obj.geojson);
                    coords = turf.point([coords.coordinates[0], coords.coordinates[1]]).geometry;
                } else {
                    coords = obj.geojson;
                    coords = turf.point([obj.geojson.coordinates[0], obj.geojson.coordinates[1]]).geometry;
                }
                var coords2;
                if (data.viatura) {
                    coords2 = data.geojson;
                    if (coords2 != null && coords2.geometry != null && coords2.geometry.coordinates != null) {
                        coords2 = turf.point([data.geo_point.lon, data.geo_point.lat]).geometry;
                    } else if (coords2 != null && coords2.coordinates != null) {
                        coords2 = turf.point([data.geojson.coordinates[0], data.geojson.coordinates[1]]).geometry;
                    }
                } else {
                    coords2 = data.geojson != null ? JSON.parse(data.geojson) : data.geometry.geometry;
                }

                var distancia = turf.distance(
                    turf.point([coords.coordinates[1], coords.coordinates[0]]),
                    turf.point([coords2.coordinates[1], coords2.coordinates[0]]),
                    'miles');

                MapaService.adicionarSubItem(coords, coords2, (distancia * 1609).toFixed(0) + ' m', subItens);
            },
            /**
             * @method abrirIncidente
             * @param {*} id 
             * @param {*} latlng 
             * @param {*} marker 
             */
            'abrirIncidente': function (id, latlng, marker) {
                this.ativo = true;

                $timeout(function () {

                    var detalhamento = MainState.getDirective('detalhamento');
                    var MSIManager = MainState.getManager('MSIManager');

                    if(detalhamento){
                        var incidente = detalhamento.buscarIncidente(id, latlng, marker);
                    }

                    MapaService.removerLinhas();
                    MSIManager.gotoIncidente(id);
                    MainState.detalhamentosAtivos.detalhamento = this;

                    return incidente;
                }, 100);

            },
            /**
             * @method abrirCamera
             * @param {*} url 
             * @param {*} largura 
             * @param {*} altura 
             */
            'abrirCamera': function (url, largura, altura) {
                window.open(url, '_blank', 'toolbar=no,location=no,status=no,menubar=no,scrollbars=false,resizable=false,width=' + largura + ',height=' + altura);
            },
            /**
             * @method abrirPoi
             */
            'abrirPoi': function (id, latlng, tipo) {
                this.ativo = true;

                this.poiAtivo = id;
                $timeout(function () {
                    var detalhamento = MainState.getDirective('detalhamento');
                    detalhamento.buscarPoi(id, latlng, tipo);
                    MainState.detalhamentosAtivos.detalhamento = this;
                }, 100);

            },
            /**
             * @method abrirViatura
             * @param {*} viatura 
             */
            'abrirViatura': function (viatura) {
                this.ativo = true;

                MapaService.removerLinhas();
                $timeout(function () {
                    var detalhamento = MainState.getDirective('detalhamento');
                    detalhamento.carregarViatura(viatura);
                }, 100);

                MainState.detalhamentosAtivos.detalhamento = this;
            },
            /**
             * @method abrir
             * @param {*} download 
             * @param {*} payload 
             */
            'abrir': function (download, payload) {
                this.ativo = true;
                MainState.detalhamentosAtivos.detalhamento = this;
            },
            /**
             * @method abrirPlanejamento
             * @param {*} id 
             * @param {*} latlng 
             */
            'abrirPlanejamento': function (id, latlng) {
                this.ativo = true;

                MapaService.removerLinhas();
                $timeout(function () {
                    var detalhamento = MainState.getDirective('detalhamento');
                    detalhamento.buscarPlanejamento(id, latlng);
                }, 100);

                MainState.detalhamentosAtivos.detalhamento = this;
            },
            /**
             * @method abrirZonaDeObservacao
             * @param {*} data 
             */
            'abrirZonaDeObservacao': function (data) {
                var id = data.zonaDeObservacao ? data.zonaDeObservacao.id : data

                ZonaObservacaoService
                    .pegarZona(id)
                    .then(function (zo) {
                        ZonaDeObservacaoManager.abrirExistente(zo, data);
                    });
            },
            /**
             * @method abrirRota
             * @param {*} data 
             */
            'abrirRota': function (data) {
                this.ativo = true;
                $timeout(function () {
                    var detalhamento = MainState.getDirective('detalhamento');
                    detalhamento.buscarRota(data);
                }, 100);

                MainState.detalhamentosAtivos.detalhamento = this;
            },
            
            /**
             * @method resetarDetalhamento
             * @param {*} subItens 
             */
            'resetarDetalhamento': function (subItens) {
                var deferred = $q.defer();

                MapaService.resetarDetalhamento(subItens ? subItens.getLayers() : []);

                if (MainState.getDirective('detalhamento')) {
                    MainState.getDirective('detalhamento').apagarDetalhamento();
                }

                return deferred.promise;
            },
            /**
             * @method abrirMosaicoCameras
             * @param {*} ponto 
             * @param {*} cameras 
             */
            'abrirMosaicoCameras': function (ponto, cameras) {
                MapaService.removerLinhas();
                MapaService.showCameras(ponto, cameras);
                MapaService.drawCameraLines(ponto, cameras);
            },
            'setManagers': function (mgrs) {
                this.managers = mgrs;
            },
            /**
             * @method fechar
             */
            'fechar': function () {

                var SubDetalhamentoManager = MainState.getManager('SubDetalhamentoManager');
                var self = this;

                this.ativo = false;
                MapaService.removerRouterRotaUnificada();
                MapaService.removerPoiClicado();
                MapaService.removerLinhas();
                MapaService.changeClass(false);
                self.ativo = false;
                MapaService.removerLayers(subItens.getLayers());
                subItens.clearLayers();

                var msi = MainState.getDirective('filtro-msi');
                if (msi) {
                    msi.gotoIncidente(-1);
                }

                if (SubDetalhamentoManager != null) {
                    SubDetalhamentoManager.fechar();
                }

                if (MainState.managers.IncidentesManager) {
                    MainState.managers.IncidentesManager.incidenteAtivo = {};
                }

                delete MainState.detalhamentosAtivos.detalhamento;
                delete MainState.detalhamentosAtivos.subDetalhamento;
                delete MainState.detalhamentosAtivos.planejamento;
                delete MainState.detalhamentosAtivos.zonaObservacao;
                delete MainState.detalhamentosAtivos.rotas_unificadas;
                var detalhamento = MainState.getDirective('detalhamento');
                if (detalhamento) {
                    detalhamento.removerPoisRelacionados(null);
                }

            },
            /**
             * @method fecharTodos
             */
            'fecharTodos': function(){
                this.fechar();
                this.managers.forEach(function (manager) {
                    manager.ativo = false;
                });
            }
        };
    }

    DetalhamentoManager.$inject = [
        'MainState',
        '$q',
        '$mdDialog',
        'MapaService',
        '$timeout',
        'ZonaObservacaoService',
        'ZonaDeObservacaoManager'
    ];

    angular.module('s4c.managers')
        .service('DetalhamentoManager', DetalhamentoManager);
})();