angular.module('starter.utils', [])

  .factory('utilService', ["$ionicLoading", "$ionicPlatform", "$cordovaFile", "constants", "$http", "$rootScope", "$ionicModal", "$cordovaInAppBrowser", "$cordovaSocialSharing", "$ionicPopover", '$ionicPopup',
    function ($ionicLoading, $ionicPlatform, $cordovaFile, constants, $http, $rootScope, $ionicModal, $cordovaInAppBrowser, $cordovaSocialSharing, $ionicPopover, $ionicPopup) {
      var utilService = {};
        utilService.getParamByName = function (name, params) {
            for(var i=0; i<params.length;i++)
            {
                if(params[i].name == name)
                {
                    return params[i];
                }
            }

            return 0;
        };

        utilService.getBookChapters = function (bookID, allChapter) {
            var chapters = [];
            for(var i=0; i<allChapter.length;i++)
            {
                if(allChapter[i].book_id == bookID)
                {
                    chapters.push(allChapter[i]);
                }
            }

            return chapters;
        };

        utilService.CheckOnline = function (callbackonline, callbackoffline) {

        if (!window.cordova) {
          //in browser
          callbackonline();
        }
        else {
          $ionicPlatform.ready(function () {
            if (window.Connection) {
              if (navigator.connection.type == Connection.NONE || navigator.connection.type == Connection.UNKNOWN) {
                callbackoffline();
              }
              else {
                callbackonline();
              }
            }
            else {
              callbackoffline();
            }
          });
        }
      };


      utilService.saveNewTokenToBackend = function (resultreg) {
        var platform = "android";
        if (ionic.Platform.isIOS() || ionic.Platform.isIPad()) {
          platform = "ios";
        }
        console.log("I am on " + platform);
        console.log("I regestered token and my token is " + resultreg + " lets save to the backend and file");
        var savetokenurl = constants.regdevicetoken + "?device_token=" + resultreg + "&device_type=" + platform;
        alert(savetokenurl);
        $http({
          method: "GET",
          url: savetokenurl
        }).success(function (data) {
          window.localStorage.setItem("didRegToken", "reged");
          window.localStorage.setItem("token", resultreg);



        }).error(function (data, status) {
          alert("err " + data + " status " + status);
        });
      };


      utilService.initFontSizes = function (scopeObj) {
        scopeObj.FontSizeList = [


          {id: "3", name: "متوسط", value: "100%"},
          {id: "4", name: "كبير", value: "120%"},
          {id: "5", name: "كبير جدا", value: "140%"}
        ];
      };

      utilService.openSocial = function (social) {
        var options = {
          location: 'no',
          clearcache: 'no',
          toolbar: 'no'
        };
        if (social == "email") {
          $cordovaSocialSharing
            .shareViaEmail("بسم الله الرحمن الرحيم" + "\r\n" + "اللهم صل على محمد وآل محمد" + "\r\n", "بخصوص تطبيق القديح 24", ["qudaih24@gmail.com"])
            .then(function (result) {
              // Success!
            }, function (err) {
              // An error occurred. Show a message to the user
            });
          return;
        }

        var socialUrl = "";


        if (social == 'fb') {
          socialUrl = "https://www.facebook.com/alqudaih24/";
        }
        else if (social == 'tw') {
          socialUrl = "https://twitter.com/qudaih24";
        }
        else if (social == 'ig') {
          socialUrl = "https://www.instagram.com/qudaih24/";
        }
        else if (social == 'yt') {
          socialUrl = "https://www.youtube.com/channel/UCStbzix-zNQW7Hi-DL7XIvw";
        }
        else if (social == 'telegram') {
          socialUrl = "https://telegram.me/qudaih24";
        }

        $cordovaInAppBrowser.open(socialUrl, '_system', options)
          .then(function (event) {
          })
          .catch(function (event) {
          });
      };

      utilService.shareApp = function () {
        var message = constants.sendtofriendsubject + "\r\n" + "للآيفون و الآيباد" + "\r\n" + constants.shareappiosurl + "\r\n" + "للاندرويد" + "\r\n" + constants.shareappandroidurl;
        $cordovaSocialSharing
          .share(message) // Share via native share sheet
          .then(function (result) {
            // Success!
          }, function (err) {
            // An error occured. Show a message to the user
          });
      };

      utilService.rateApp = function () {
        if ($ionicPlatform.is('ios')) {
          window.open(constants.rateiosurl, '_system'); // or itms://
        } else if ($ionicPlatform.is('android')) {
          window.open(constants.rateandroidurl, '_system');
        }
      };

      utilService.opennoorw = function () {
        var options = {
          location: 'no',
          clearcache: 'no',
          toolbar: 'no'
        };
        $cordovaInAppBrowser.open("http://noorwilaya.com", '_system', options)
          .then(function (event) {
          })
          .catch(function (event) {
          });
      };

      utilService.ToIndiaDigits = function (text) {
        var id = ['۰', '۱', '٢', '۳', '٤', '٥', '٦', '۷', '۸', '۹'];
        return text.replace(/[0-9]/g, function (w) {
          return id[+w]
        });
      };

      utilService.openurl = function (url) {
        var options = {
          location: 'no',
          clearcache: 'no',
          toolbar: 'no'
        };
        $cordovaInAppBrowser.open(url, '_system', options)
          .then(function (event) {
          })
          .catch(function (event) {
          });
      };

      utilService.initSharePopOver = function (scopeObj) {
        $ionicPopover.fromTemplateUrl('templates/popover.html', {
          scope: scopeObj
        }).then(function (popover) {
          scopeObj.popover = popover;

        });

        scopeObj.showPopoOver = function ($event) {
          scopeObj.popover.show($event);
        };
        scopeObj.hidePopoOver = function () {
          scopeObj.popover.hide();
        };
      };


      utilService.getBookNameByid = function (bookid) {
        var bookname;
        if( $rootScope.bookList)
        {
          for (var i = 0; i < $rootScope.bookList.length; i++) {
            if ($rootScope.bookList[i].id == bookid) {
              bookname = $rootScope.bookList[i].name;
            }
          }
        }
        else
        {

        }

        return bookname;
      };
      utilService.showAlert = function (message) {
        $ionicPopup.alert({
            okText: 'إغلاق',
            okType: 'button-balanced',
            title: 'تنبيه',
          template: message
        });
      };

      utilService.validateEmail = function (email) {
        var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(email);
      };

      utilService.togglePush = function (callback) {

        var online = function () {

          var token=window.localStorage.getItem("token");
          var platform = "android";
          if (ionic.Platform.isIOS() || ionic.Platform.isIPad()) {
            platform = "ios";
          }
          var togglePushUrl=constants.togglepushurl+"?device_token="+token+"&device_type="+platform;

          console.log("togglePushUrl "+togglePushUrl);
          $http({
            method: 'GET',
            url:togglePushUrl
          }).then(function successCallback(data) {
            if(callback)
            {
                callback();
            }
            }, function errorCallback(response) {
              if(callback)
              {
                  callback();
              }
                alert("error1 response: " + response );
            });

        };

        var offline = function () {
          $ionicLoading.hide();

        };


        utilService.CheckOnline(online,offline);
      };

      utilService.getPushSub=function (scopeObj,callback) {
        console.log("here");
        var online = function () {

          var token=window.localStorage.getItem("token");
          var platform = "android";
          if (ionic.Platform.isIOS() || ionic.Platform.isIPad()) {
            platform = "ios";
          }
          var pushSubUrl=constants.pushsuburl+"?device_token="+token+"&device_type="+platform;
          console.log("pushSubUrl "+pushSubUrl);
          $http({
            method: 'GET',
            url:pushSubUrl
          }).then(function successCallback(data) {
            if(data.status=="yes")
            {
              scopeObj.subscribed=true;
            }
            else
            {
              scopeObj.subscribed=false;
            }
            if(callback)
            {
              callback();
            }
          }, function errorCallback(response) {
            if(callback)
            {
              callback();
            }
            alert("error1 response: " + response );
          });

        };

        var offline = function () {
          $ionicLoading.hide();

        };


        utilService.CheckOnline(online,offline);
      };

      utilService.contactus=function () {
        var platform = "Android";
        if (ionic.Platform.isIOS() || ionic.Platform.isIPad()) {
          platform = "iOS";
        }
        var message="بخصوص تطبيق فقهيات 1.0 "+platform;

        var subject="بسم الله الرحمن الرحيم" +"\r\n"+"اللهم صل على محمد وآل محمد"+ "\r\n";
        var toArr=["feqhiatapp@gmail.com"];
        $cordovaSocialSharing
          .shareViaEmail(message, subject, toArr)
          .then(function(result) {
            // Success!
          }, function(err) {
            // An error occurred. Show a message to the user
          });
      };


      return utilService;
    }]);
