var TaxiApp = angular.module('Cities', ['ngStorage', 'ngDialog', 'angularUtils.directives.dirPagination', 'ui.bootstrap']);
var company, TariffList;

TaxiApp.controller('EditTariffCtrl', function ($scope, $http, $sessionStorage, ngDialog, $window, obj) {

    $scope.ClickClose = function () {
        $(".ngdialog-close").trigger("click");

    }
})

TaxiApp.controller('CitiesCtrl', ['$scope', '$http', '$sessionStorage', 'ngDialog',
    function ($scope, $http, $sessionStorage, ngDialog, $confirm) {
        $scope.Role = sessionStorage.RoleType;
        $scope.RoleID = sessionStorage.RoleID;
        $scope.DisplayName = sessionStorage.UserName;
        $scope.CompanyName = sessionStorage.value;
        $scope.regionMarker;

        if (sessionStorage.OrderId < 2) {
            window.location.href = "../../Access.html";
        }
        else {
            Localization(sessionStorage.selectedLanguage, 'user', $scope, sessionStorage);
            $scope.loading = true;
            // $('.driveradd').hide();

            if (sessionStorage.length == (undefined || 0)) {
                window.parent.location.href = "../../Index.html";
            }
            else {
                var TokenID = sessionStorage.TokenID;
                var orgOID = sessionStorage.ORGOID;
                var userOID = sessionStorage.UserOID;
                var roleType = sessionStorage.RoleType;
                var roleID = sessionStorage.RoleID;
                var companyOID = sessionStorage.CompanyOID;

                $scope.Role = sessionStorage.RoleType;

                loadDropDownFromAppConfig("CARTYPE", userOID, companyOID, orgOID, 0, $scope);
                loadCurrencyTypes($scope);

                // console.log($scope.CARTYPE)

                loadDropDownFromAppConfig("Group", sessionStorage.UserOID, sessionStorage.CompanyOID, sessionStorage.ORGOID, 0, $scope);
                if (sessionStorage.CompanyOID != undefined || sessionStorage.ORGOID != undefined) {
                    loadDropDownFromAppConfig("COMPANY", sessionStorage.UserOID, sessionStorage.CompanyOID, sessionStorage.ORGOID, 0, $scope);
                }

                loadContents(sessionStorage.ORGOID, sessionStorage.CompanyOID, sessionStorage.UserOID, 'DT', $scope);

                $scope.currentPage = 1

                $scope.Cities = {
                    // Initialize and add the map
                    drawPolygon: function (div) {
                        if ($scope.regionMarker != null) {
                            $scope.regionMarker.setMap(null);
                        }
                        $scope.map = new google.maps.Map(document.getElementById(div), {
                            center: { lat: 21.6227, lng: 39.3519 },
                            zoom: 8
                        });


                       
                    var drawingManager = new google.maps.drawing.DrawingManager({
                            drawingMode: google.maps.drawing.OverlayType.POLYGON,
                            drawingControl: false,
                            drawingControlOptions: {
                                position: google.maps.ControlPosition.TOP_CENTER,
                                drawingModes: ['polygon']
                            }
                        });

                        drawingManager.setMap($scope.map);
                        google.maps.event.addListener(drawingManager, 'overlaycomplete', (event) => {
                            if ($scope.regionMarker != null) {
                                $scope.regionMarker.setMap(null);
                            }                            $scope.regionMarker = event.overlay;
                            // Polygon drawn
                            if (event.type === google.maps.drawing.OverlayType.POLYGON) {
                                var wkt = "POLYGON(";

                                //this is the coordinate, you can assign it to a variable or pass into another function.
                                var paths = event.overlay.getPaths();
                                for (var i = 0; i < paths.getLength(); i++) {
                                    var path = paths.getAt(i);

                                    // Open a ring grouping in the Polygon Well Known Text
                                    wkt += "(";
                                    for (var j = 0; j < path.getLength(); j++) {
                                        // add each vertice and anticipate another vertice (trailing comma)
                                        wkt += path.getAt(j).lng().toString() + " " + path.getAt(j).lat().toString() + ",";
                                    }

                                    // Google's approach assumes the closing point is the same as the opening
                                    // point for any given ring, so we have to refer back to the initial point
                                    // and append it to the end of our polygon wkt, properly closing it.
                                    //
                                    // Also close the ring grouping and anticipate another ring (trailing comma)
                                    wkt += path.getAt(0).lng().toString() + " " + path.getAt(0).lat().toString() + "),";
                                }

                                // resolve the last trailing "," and close the Polygon
                                wkt = wkt.substring(0, wkt.length - 1) + ")";

                                $scope.e_Geom = wkt;

                              
                            }
                        });
                    },

                    addRegion: function (region) {
                        if ($scope.regionMarker != null) {
                            $scope.regionMarker.setMap (null);
                        }
                        var wkt = region; //this is your WKT string

                        //using regex, we will get the indivudal Rings
                        var regex = /\(([^()]+)\)/g;
                        var Rings = [];
                        var results;
                        while (results = regex.exec(wkt)) {
                            Rings.push(results[1]);
                        }

                        var ptsArray = [];

                        var polyLen = Rings.length;

                        //now we need to draw the polygon for each of inner rings, but reversed
                        for (var i = 0; i < polyLen; i++) {
                            AddPoints(Rings[i]);
                        }

                        $scope.regionMarker = new google.maps.Polygon({
                            paths: ptsArray,
                            strokeColor: '#1E90FF',
                            strokeOpacity: 0.8,
                            strokeWeight: 2,
                            fillColor: '#1E90FF',
                            fillOpacity: 0.35
                        });

                        $scope.regionMarker.setMap($scope.map);


                        //function to add points from individual rings
                        function AddPoints(data) {
                            //first spilt the string into individual points
                            var pointsData = data.split(",");


                            //iterate over each points data and create a latlong
                            //& add it to the cords array
                            var len = pointsData.length;
                            for (var i = 0; i < len; i++) {
                                var xy = pointsData[i].trim().split(" ");

                                var pt = new google.maps.LatLng(xy[1].trim(), xy[0].trim());
                                ptsArray.push(pt);
                            }


                        }
                        var bounds = new google.maps.LatLngBounds();
                        var paths = $scope.regionMarker.getPaths();
                        var path;
                        for (var i = 0; i < paths.getLength(); i++) {
                            path = paths.getAt(i);
                            for (var ii = 0; ii < path.getLength(); ii++) {
                                bounds.extend(path.getAt(ii));
                            }
                        }
                        $scope.map.fitBounds(bounds);
                        zoomChangeBoundsListener =
                            google.maps.event.addListenerOnce($scope.map, 'bounds_changed', function (event) {
                                if (this.getZoom()) {
                                    this.setZoom(12);
                                }
                            });
                        setTimeout(function () { google.maps.event.removeListener(zoomChangeBoundsListener) }, 2000);
                    },

                    get: function () {
                        $.ajax({
                            cache: true,
                            url: ManagementServiceUrl + "GetCities/" + userOID +"/"+sessionStorage.TokenID,
                            type: "GET",
                            contentType: "application/javascript",
                            dataType: "jsonp",
                            success: function (result) {
                                if (result.GetCitiesResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                $scope.citieslist = JSON.parse(result.GetCitiesResult);
                                //  console.log($scope.driverList)
                                $scope.loading = false;
                                $scope.$apply();
                            }
                        });
                    },
                    add: function () {
                        $scope.e_OID = null;
                        $scope.e_Name = "";
                        $scope.e_SearchDistance = '';
                        $scope.e_CustomerPoints = '';
                        $scope.e_DriverPoints = '';
                        $scope.e_CustomerPointsPerUnit = '';
                        $scope.e_DriverPointsPerUnit = '';
                        $scope.e_CustomerPointsConversionRate = '';
                        $scope.e_DriverPointsConversionRate = '';
                        $scope.e_Geom = '';
                        $scope.Cities.drawPolygon("map2");

                        $('#AddModal').modal('toggle');
                    },
                    
                    saveNew: function() {
                        if ($scope.e_Name == undefined || $scope.e_Name == "" ||
                            $scope.e_SearchDistance == undefined || $scope.e_SearchDistance == "" ||
                            $scope.e_CustomerPoints == undefined || $scope.e_CustomerPoints == "" ||
                            $scope.e_DriverPoints == undefined || $scope.e_DriverPoints == "" ||
                            $scope.e_CustomerPointsPerUnit == undefined || $scope.e_CustomerPointsPerUnit == "" ||
                            $scope.e_DriverPointsPerUnit == undefined || $scope.e_DriverPointsPerUnit == "" ||
                            $scope.e_CustomerPointsConversionRate == undefined || $scope.e_CustomerPointsConversionRate == "" ||
                            $scope.e_DriverPointsPerUnit == undefined || $scope.e_DriverPointsPerUnit == "" ||
                            $scope.e_CustomerPointsConversionRate == undefined || $scope.e_CustomerPointsConversionRate == "" ||
                            $scope.e_DriverPointsConversionRate == undefined || $scope.e_DriverPointsConversionRate == "" ||
                            $scope.e_Geom == undefined || $scope.e_Geom == ""
                        ) {
                            alert("يرجى ادخال جميع الحقول")
                            return;
                        }
                        var city = {
                            "CityName": $scope.e_Name,
                            "SearchDistance": $scope.e_SearchDistance,

                            "CustomerPoints": $scope.e_CustomerPoints,
                            "DriverPoints": $scope.e_DriverPoints,

                            "CustomerPointsPerUnit": $scope.e_CustomerPointsPerUnit,
                            "DriverPointsPerUnit": $scope.e_DriverPointsPerUnit,

                            "CustomerPointsConversionRate": $scope.e_CustomerPointsConversionRate,
                            "DriverPointsConversionRate": $scope.e_DriverPointsConversionRate,

                            "geom": $scope.e_Geom,
                            "ModifiedBy": sessionStorage.UserOID,
                            "TokenID": sessionStorage.TokenID

                        }
                        var obj = {};

                        obj["obj"] = city;
                        $.ajax({
                            type: "POST",
                            url: ManagementServiceUrl + "AddCityDtls",
                            data: JSON.stringify(obj),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            processData: true,
                            success: function (data) {
                                if (data.UpdateDriverResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                var res = JSON.parse(data.AddCityDtlsResult);
                                // var str = "Hello world, welcome to the universe.";

                                //  console.log(res)
                                if (res = 'success') {
                                    $('#EditModal').modal('toggle');
                                    $scope.Cities.get()

                                } else {
                                    alert(res + "حدث خطأ  ")

                                }
                            }
                        });

                    },
                    edit: function (e) {
                        $scope.e_OID = e.OID;
                        $scope.e_Name = e.CityName;
                        $scope.e_SearchDistance = e.SearchDistance;
                        $scope.e_CustomerPoints = e.CustomerPoints;
                        $scope.e_DriverPoints = e.DriverPoints;
                        $scope.e_CustomerPointsPerUnit = e.CustomerPointsPerUnit;
                        $scope.e_DriverPointsPerUnit = e.DriverPointsPerUnit;
                        $scope.e_CustomerPointsConversionRate = e.CustomerPointsConversionRate;
                        $scope.e_DriverPointsConversionRate = e.DriverPointsConversionRate;
                        $scope.e_Geom = e.geom;
                        $scope.Cities.drawPolygon("map1");
                        this.addRegion(e.geom);

                        $('#EditModal').modal('toggle');
                    },
                    saveEdits() {
                        if ($scope.e_Name == undefined || $scope.e_Name == "" ||
                            $scope.e_SearchDistance == undefined || $scope.e_SearchDistance == "" ||
                            $scope.e_CustomerPoints == undefined || $scope.e_CustomerPoints == "" ||
                            $scope.e_DriverPoints == undefined || $scope.e_DriverPoints == "" ||
                            $scope.e_CustomerPointsPerUnit == undefined || $scope.e_CustomerPointsPerUnit == "" ||
                            $scope.e_DriverPointsPerUnit == undefined || $scope.e_DriverPointsPerUnit == "" ||
                            $scope.e_CustomerPointsConversionRate == undefined || $scope.e_CustomerPointsConversionRate == "" ||
                            $scope.e_DriverPointsPerUnit == undefined || $scope.e_DriverPointsPerUnit == "" ||
                            $scope.e_CustomerPointsConversionRate == undefined || $scope.e_CustomerPointsConversionRate == "" ||
                            $scope.e_DriverPointsConversionRate == undefined || $scope.e_DriverPointsConversionRate == "" ||
                            $scope.e_Geom == undefined || $scope.e_Geom == "" 
                            ) {
                            alert("يرجى ادخال جميع الحقول")
                            return;
                        } 
                        var city = {
                            "OID": $scope.e_OID,
                            "CityName": $scope.e_Name,
                            "SearchDistance": $scope.e_SearchDistance,

                            "CustomerPoints": $scope.e_CustomerPoints,
                            "DriverPoints": $scope.e_DriverPoints,

                            "CustomerPointsPerUnit": $scope.e_CustomerPointsPerUnit,
                            "DriverPointsPerUnit": $scope.e_DriverPointsPerUnit,

                            "CustomerPointsConversionRate": $scope.e_CustomerPointsConversionRate,
                            "DriverPointsConversionRate": $scope.e_DriverPointsConversionRate,

                            "geom": $scope.e_Geom,
                            "ModifiedBy": sessionStorage.UserOID,
                            "TokenID": sessionStorage.TokenID

                        }
                        var obj = {};

                        obj["obj"] = city;
                        $.ajax({
                            type: "POST",
                            url: ManagementServiceUrl + "UpdateCityDtls",
                            data: JSON.stringify(obj),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            processData: true,
                            success: function (data) {
                                if (data.UpdateCityDtlsResult == "access_denied") {
                                    window.parent.location.href = "../../Access.html";
                                    return;
                                }
                                var res = JSON.parse(data.UpdateCityDtlsResult);
                                // var str = "Hello world, welcome to the universe.";

                                //  console.log(res)
                                if (res='success') {
                                    $('#EditModal').modal('toggle');
                                    $scope.Cities.get()

                                } else {
                                    alert(res + "حدث خطأ  ")

                                }




                            },
                        });


                    }

                }

                TariffList = $scope.TariffList;
                $scope.SelectCity = function (cityOid) {
                    $scope.TariffList.get(cityOid)
                }

                $scope.Cities.get();


            }
        }
    }]);



