﻿(function () {
    "use strict";
    mekkahExplorerApp.directive('measurement', function () {
        return {
            scope: {
                widget:"="
            },
            replace: true,
            restrict: 'E',
            template: '<div ng-include="templateUrl"></div>',
            controller: [
                '$scope', '$timeout', '$sce', '$rootScope', '$http', '$filter', '$window', '$q', 'mapService', 'helper', function ($scope, $timeout, $sce, $rootScope, $http, $filter, $window, $q, mapService, helper) {
                    $scope.templateUrl = window.appPath + 'app/Directives/Measurement/measurement.tbl.htm?cv=' + window.cv;
                    $scope.mapService = mapService;

                    $scope.widget.close = function () {
                        $scope.clearMeasurements();
                    }

                    $scope.$on("$destroy", function () {
                        if ($scope.mapService.drawingsLayerSegmentLabels) {
                            $scope.mapService.drawingsLayerSegmentLabels.removeAll();
                            $scope.mapService.drawingsLayerSegmentLabels.destroy();
                        }
                    });

                    function getLabelSymbol(text) {
                        var lineColor = helper.hexToRgb('#ffffff');//graphic.attributes.symbol.lineColor
                        var fillColor = helper.hexToRgb('#7A7A7A');//graphic.attributes.symbol.fillColor
                        var textSymbol = {
                            type: "text",
                            color: [lineColor.r, lineColor.g, lineColor.b, 1],
                            haloColor: [fillColor.r, fillColor.g, fillColor.b, 1],
                            haloSize: "2px",
                            text: text,
                            font: {
                                size: 12,
                                family: "Arial",
                                weight: "bold"
                            },
                            xoffset: "1px",
                            yoffset: "1px"
                        };
                        return textSymbol;
                    }
                    function addLabel(startPoint, endPoint, wkid,lbl) {
                        var centerPoint = {
                            type: "point",
                            x: (startPoint[0] + endPoint[0])/2,
                            y: (startPoint[1] + endPoint[1]) / 2,
                            spatialReference: wkid
                        };
                        var pointGraphic = new mapService.EsriGraphic({
                            geometry: centerPoint,
                            symbol: getLabelSymbol(lbl),
                            spatialReference: wkid
                        });
                        $scope.mapService.drawingsLayerSegmentLabels.add(pointGraphic);
                    }

                    function calcLengthOfPolylineSegment(startPoint, endPoint, wkid, unit) {
                        let paths = [
                            [
                                [startPoint[0], startPoint[1]],
                                [endPoint[0], endPoint[1]]
                            ]
                        ];

                        let line = new mapService.EsriPolyline({
                            hasZ: false,
                            hasM: true,
                            paths: paths,
                            spatialReference: { wkid: wkid }
                        });
                        if (unit == "inch") {
                            return parseFloat(mapService.EsriGeometryEngine.planarLength(line, "meters")) * 39.3701;
                        } else {
                            return parseFloat(mapService.EsriGeometryEngine.planarLength(line, unit));
                        }
                    }

                    $scope.getUnitLabel = function (measurementLabel) {
                        var arrOfMeasurementLabel = measurementLabel.split(' ');
                        var unitLabel = '';
                        for (var i = 1; i < arrOfMeasurementLabel.length; i++) {
                            if (unitLabel.length == 0)
                                unitLabel = unitLabel + arrOfMeasurementLabel[i];
                            else
                                unitLabel = unitLabel +' '+ arrOfMeasurementLabel[i];

                        }
                        return unitLabel;
                    }

                    $scope.$on("$includeContentLoaded", function (event, templateName) {
  
                        $scope.activeTool = 'none';
                        $scope.measurement = new mapService.EsriMeasurement({
                            container: document.getElementById("measurementToolWidget"),
                        });



                        mapService.view.ui.add($scope.measurement, "manual");

                        $scope.mapService.drawingsLayerSegmentLabels = new $scope.mapService.EsriGraphicsLayer({
                            title: 'طبقة ملصقات القياسات',
                            listMode: "hide",
                            visible: false
                        });

                        $scope.mapService.view.map.layers.add($scope.mapService.drawingsLayerSegmentLabels);

                        //1 m  = 39.3701
                        $scope.measurement.watch("viewModel.activeViewModel.measurementLabel", function (label) {

                            if ($scope.measurement.viewModel.activeViewModel.measurement && $scope.measurement.viewModel.activeViewModel.measurement.geometry) {
                                $scope.mapService.drawingsLayerSegmentLabels.removeAll();
                                var index = $scope.mapService.view.map.layers.length - 1;
                                $scope.mapService.view.map.layers.reorder($scope.mapService.drawingsLayerSegmentLabels, index);
                                var geometry = $scope.measurement.viewModel.activeViewModel.measurement.geometry;
                                var unit = "meters";
                                var measurementLabel;
                                if ($scope.measurement.viewModel.activeViewModel.measurementLabel.perimeter)
                                    measurementLabel = $scope.measurement.viewModel.activeViewModel.measurementLabel.perimeter;
                                else
                                    measurementLabel = $scope.measurement.viewModel.activeViewModel.measurementLabel;

                                var arrOfMeasurementLabel = measurementLabel.split(' ');

                                if (encodeURIComponent(arrOfMeasurementLabel[1]) == '%D9%83%D9%8A%D9%84%D9%88%D9%85%D8%AA%D8%B1')
                                    unit = "kilometers";
                                else if (encodeURIComponent(arrOfMeasurementLabel[1]) == '%D9%85%D8%AA%D8%B1')
                                    unit = "meters";
                                else if (encodeURIComponent(arrOfMeasurementLabel[1]) == '%D9%82%D8%AF%D9%85')
                                    unit = "feet";
                                else if (encodeURIComponent(arrOfMeasurementLabel[1]) == '%D9%81%D9%8A')
                                    unit = "inch";
                                else if (encodeURIComponent(arrOfMeasurementLabel[1]) == '%D9%8A%D8%A7%D8%B1%D8%AF')
                                    unit = "yards";
                                else if (arrOfMeasurementLabel.length == 3 && encodeURIComponent(arrOfMeasurementLabel[2]) == '%D8%A8%D8%AD%D8%B1%D9%8A')
                                    unit = "nautical-miles";
                                else if (encodeURIComponent(arrOfMeasurementLabel[1]) == '%D9%85%D9%8A%D9%84')
                                    unit = "miles";


                                if (geometry.type == "polyline") {
                                    for (var i = 0; i < geometry.paths[0].length - 1; i++) {
                                        var startPoint = geometry.paths[0][i];
                                        var endPoint = geometry.paths[0][i + 1];
                                        var segmentLength = calcLengthOfPolylineSegment(startPoint, endPoint, geometry.spatialReference.wkid, unit);
                                        addLabel(startPoint, endPoint, geometry.spatialReference.wkid, segmentLength.toFixed(2) + ' ' + $scope.getUnitLabel(measurementLabel))

                                    }
                                } else if (geometry.type == "polygon") {
                                    for (var i = 0; i < geometry.rings[0].length - 1; i++) {
                                        var startPoint = geometry.rings[0][i];
                                        var endPoint = geometry.rings[0][i + 1];
                                        var segmentLength = calcLengthOfPolylineSegment(startPoint, endPoint, geometry.spatialReference.wkid, unit);
                                        addLabel(startPoint, endPoint, geometry.spatialReference.wkid, segmentLength.toFixed(2) + ' ' + $scope.getUnitLabel(measurementLabel))

                                    }
                                }

                            } else {
                                $scope.mapService.drawingsLayerSegmentLabels.removeAll();
                            }
                        });


                        $scope.measurement.view = mapService.view;

                        $("#measurementToolWidget").attr("id", "measurementToolWidget").appendTo("#measurementTool");

                        $scope.distanceMeasurement = function () {
                            var type = mapService.view.type;
                            $scope.measurement.activeTool = type.toUpperCase() === "2D" ? "distance" : "direct-line";
                            $scope.activeTool = 'line';
                        }
                        $scope.areaMeasurement = function () {
                            $scope.measurement.activeTool = "area";
                            $scope.activeTool = 'area';
                        }
                        $scope.clearMeasurements = function () {
                            $scope.measurement.clear();
                            $scope.activeTool = 'none';
                            if ($scope.mapService.drawingsLayerSegmentLabels) {
                                $scope.mapService.drawingsLayerSegmentLabels.removeAll();
                            }
                        }
                        $timeout(function () {
                            $scope.distanceMeasurement();
                        }, 100);
                        

                        function toolLoaded(callBack, key) {
                            if (document.getElementById(key) == null) {
                                $timeout(function () { toolLoaded(callBack, key) }, 100);
                            }
                            else if (document.getElementById(key).getElementsByTagName("*").length <= 1) {
                                $timeout(function () { toolLoaded(callBack, key) }, 100);
                            } else {
                                if (callBack) {
                                    callBack();
                                }
                            }
                        }

                        toolLoaded(function(){
                            $scope.clearMeasurements();

                        }, 'measurementTool');

                    });
                }
            ]
        }
    });
})();