var TaxiApp = angular.module('PushNotificationApp', ['ngStorage', 'ngDialog', 'angularSpinner', 'angularUtils.directives.dirPagination', 'ui.bootstrap', 'angularAwesomeSlider', 'angular-growl', 'ngAnimate', 'AxelSoft']);
var Reservations;

Number.prototype.pad = function (size) {
    var s = String(this);
    while (s.length < (size || 2)) { s = "0" + s; }
    return s;
}

TaxiApp.controller('PushNotificationCtrl', ['$scope', '$http', '$sessionStorage', 'ngDialog', 'usSpinnerService', 'growl',
    function ($scope, $http, $sessionStorage, ngDialog, usSpinnerService, growl ) {
        $scope.loading = false;
        $scope.injectedObject = {};
        var obj
        var TokenID = sessionStorage.TokenID;
        var orgOID = sessionStorage.ORGOID;
        var userOID = sessionStorage.UserOID;
        var roleType = sessionStorage.RoleType;
        var roleID = sessionStorage.RoleID;
        var groupOID = 0, Status = "0,1";
        var OID = "0";
        var cOID, cName;
        var companyOID = sessionStorage.CompanyOID;
        $scope.logo = sessionStorage.Photo;
        $scope.DisplayName = sessionStorage.UserName;
        $scope.CompanyName = sessionStorage.value;
        var OLDpswd = sessionStorage.password;
        var cityOID = sessionStorage.CityID;
        var UserOID = sessionStorage.UserOID;
        var enterpriseAwesomplete;
        //Check Whether user Logged in or not
        //CheckUserLogged();
        if (sessionStorage.OrderId < 3) {
            window.location.href = "../../Access.html";
        }
        $scope.logo = sessionStorage.Photo;
        var Vehiclename, vehicle;
        if (sessionStorage.getItem('mapSettings') == undefined) {
            if (sessionStorage.CompanyOID != undefined || sessionStorage.ORGOID != undefined) {
                //GetCompanyMapSetting(sessionStorage.CompanyOID, sessionStorage.ORGOID);
            }
        }
        if (sessionStorage.CompanyOID != undefined || sessionStorage.ORGOID != undefined) {
            loadDropDownFromAppConfig("COMPANY", sessionStorage.UserOID, sessionStorage.CompanyOID, sessionStorage.ORGOID, 0, $scope);
            GetCompanyCityOID("CompanyCity", userOID, companyOID, orgOID, groupOID);
        }
        $scope.selectCompanydetails = function (obj) {
            sessionStorage.value = obj.Value;
            sessionStorage.value = obj.Value;
            window.location.href = "MapView.html";
        }
        if (sessionStorage.RoleType != "Superadmin" && sessionStorage.AllAdmins != null) {
            $scope.AdminList = JSON.parse(sessionStorage.AllAdmins);
            $scope.firstadmin = JSON.parse(sessionStorage.selectedadmin);

        }
        if (sessionStorage.length == (undefined || 0)) {

            window.parent.location.href = "../../Index.html";
        }
        $scope.User = sessionStorage.Username;
        //set cureentdate as default date in datepicker
        $scope.tdate = new Date();
        $scope.fdate = new Date();
        $scope.ScuedualList = [];
      
        Localization(sessionStorage.selectedLanguage, 'mapview', $scope, sessionStorage);

        $scope.value3 = 5;

        $scope.options2 = {
            from: 1,
            to: 10,
            floor: true,
            step: 1,
            dimension: " speed",
            vertical: false,
            callback: function (value, elt) {

            }
        }; 
        if (sessionStorage.RoleType == "Organization Admin") {
            $('.tele').show();
        }
        else {
            $('.tele').hide();
        }

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

        $scope.SelectedDistrict = function (districtOid) {
            //  console.log()

            $scope.DistrictName = $.grep($scope.DistrictList, function (item) {


                return item.OID == districtOid;
            })[0].value;
            console.log($scope.DistrictListModel)

        }
        if (sessionStorage.RoleType == "Organization Admin") {


            if ($scope.DistrictListModel == undefined) {

                ShowDistrict = 0
            } else {

                ShowDistrict = $scope.DistrictListModel;
            }



        } else {
            ShowDistrict = sessionStorage.DistrictOID;

        }

   

        $("#sendNotification").click(function () {
            $scope.loading = true;
            $scope.$apply();


            var mobile = $('#mobile').val();
            var msg = $('#msg').val();
            var title = $('#title').val();

            var city = $scope.DistrictListModel;
            var type = $('input[name=userType]:checked').val();
            var platform = $('input[name=platform]:checked').val();
            var appcode = $scope.AppCode;


            Notification.sendMessage(type, mobile, city, msg,title,  platform, appcode);
        });
        
        Notification = {

            sendMessage: function (userType, mobileNo, city, msgText, title, platform, appcode) {
                var self = this;
                var message = {};
                if (userType == null || userType == 'undefined' || userType == "") {
                    alert("يجب تحديد نوع المستخدم");
                    $scope.loading = false;
                    $scope.$apply();

                    return;
                }
                if (platform == null || platform == 'undefined' || platform == "") {
                    alert("يجب تحديد  قناة الاتصال");
                    $scope.loading = false;
                    $scope.$apply();

                    return;
                }
               
                if (platform == 'app' && (title == null || title == 'undefined' || title.length == 0)) {
                    alert("الرجاء اخال عنوان الرسالة");
                    $scope.loading = false;
                    $scope.$apply();

                    return;
                }
                if (msgText==null || msgText=='undefined' || msgText.length == 0) {
                    alert("الرجاء اخال نص الرسالة");
                    $scope.loading = false;
                    $scope.$apply();

                    return;
                }

                if (appcode == null || appcode == 'undefined' || appcode.length == 0) {
                    alert("الرجاء تحديد اسم التطبيق");
                    $scope.loading = false;
                    $scope.$apply();

                    return;
                }

                var message = {};
                message.userid = userOID;
                message.msg = msgText;
                message.title = title;
                message.city = ((city==null || city == "undefined" || city == "") ? "0" : city);
                message.token = TokenID;
                message.mobile = mobileNo;
                message.type = userType;
                message.platfrom = platform;
                message.appcode = appcode;

                var obj = {
                    "msgObj": message
                };
                $.ajax({
                 
                    type: "POST",
                    url: ManagementServiceUrl + "SendUserNotification",
                    data: JSON.stringify(obj),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    processData: true,
                    success: function (result) {
                        if (result.SendUserNotificationResult == "access_denied") {
                            window.parent.location.href = "../../Access.html";
                            return;
                        }
                        var data = result.SendUserNotificationResult;
                        $scope.loading = false;
                        if (data == "notsent")
                            alert("لم يتم ارسال الاشعار")
                        if (data == "error")
                            alert("حدث خطأ");
                        else if (data == "nousersfound")
                            alert("لا يوجد مستخدمين")
                        else
                            alert("لقد تم ارسال الرسالة بنجاح الى: "+data+" مستخدم")
                        $scope.loading = false;

                        $scope.$apply();


                    },
                    error: function () {
                        $scope.loading = false;
                        alert("حدث خطأ");
                        $scope.$apply();
                    }
                });
            },
            setMessage: function (msg) {
                $('#messagebody').val(msg);
            },
            addToMessage: function (msg) {
                var text = $('#messagebody').val();
                text = text + ' ' + msg;
                $('#messagebody').val(text);
            },
            clearMessage: function (msg) {

                $('#messagebody').val("");
            },
            send: function (obj) {
                var self = this;
                var drivers = [];
                var selectedKeys = Messages.driversList.getSelectedItems();
                if (selectedKeys) {
                    for (var s = 0; s < selectedKeys.length; s++) {
                        drivers[s] = { driverOID: selectedKeys[s].value, IMEINo: selectedKeys[s].imei };

                    }
                }
                $('#DriverMEssage :selected').each(function (i, selected) {
                });



                var message = {};
                message.companyOID = sessionStorage.CompanyOID;
                message.messageToSend = $('#messagebody').val();
                message.driversList = drivers;

                var annObj = {
                    "annObj": message
                };

                if (message.messageToSend == null || message.messageToSend == '' || drivers.length == 0) {
                    alert('الرجاء ادخال نص التعميم واختيار السائقين');
                    return;
                }
                $scope.loading = true;
                $.ajax({
                    type: "POST",
                    url: WebsiteServiceUrl + "SendAnnouncementToVehicleList",
                    data: JSON.stringify(annObj),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    processData: true,
                    success: function (result) {
                        if (result.SendAnnouncementToVehicleListResult == "access_denied") {
                            window.parent.location.href = "../../Access.html";
                            return;
                        }
                        if (result.SendAnnouncementToVehicleListResult == 1) {
                            $('#messagebody').val('');
                            self.driversList.deselectAll();

                        } else {
                            alert('فشل ارسال التعميم');
                        }



                        $scope.loading = false;
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $scope.loading = false;
                        alert("Status: " + textStatus); alert("Error: " + errorThrown);
                    }
                });
                $('.sol-option').each(function () {
                    $('input').attr('checked', false);
                });
                $('.sol-current-selection').empty();
            }


        }
}
        
])



