
angular.module('app.services')
  .factory('updateService', ['$log', '$timeout', '$q', '$http', '$rootScope', 'sparkDataService' ,'propertyCache', 'LoadingMsg' , '$filter', '$interval' , '$ionicPopup', function ($log, $timeout, $q, $http, $rootScope, sparkDataService ,propertyCache , LoadingMsg ,  $filter , $interval , $ionicPopup) {

    return {

      updateApplication: function (showMsg) {
        console.log("Checking Updates !");

        var _self = this;

        if (propertyCache.networkStatus != "online") {
          var alertPopup = $ionicPopup.alert({
            title: $filter('translate')('ApplicationIsOffline'),
            template: '<div class="nf-center nf-valign-wrapper">' +
            '<ion-spinner icon="ripple" class="nf-text-white"></ion-spinner>' +
            '<span>{{"PleaseCheckYourInternetConnectivity" | translate}}</span></div>'
          });
        } else {

          var subsResult = false;
          var checkResult = false;

          // IonicDeploy.init("configData.appType", propertyCache.config.syncIp, function () {
          IonicDeploy.init(propertyCache.config.license + "-"+configData.appType, "http://" + propertyCache.config.syncIp, function (result) {
            // IonicDeploy.init(propertyCache.config.license+"-qc_app", "http://192.168.1.68:9000", function (result) {
            subsResult = result;
            console.log("Subscribed ! ", result);
          }, function () {
            console.log("Init failed !");
          })

          IonicDeploy.check(propertyCache.config.license + "-"+configData.appType, "dev", function (checkResult) {
            console.log("Success Checked! ", checkResult);
            if (checkResult == "true") {
              checkResult = checkResult;


              /*var confirmPopup = $ionicPopup.confirm({
                title: $filter('translate')('SynchronizeData'),
                template: '{{"AreYouSureYouWantToUpdate" | translate }} '
              });
              confirmPopup.then(function(res) {
                if(res) {*/

                  IonicDeploy.download(propertyCache.config.license + "-"+configData.appType, function (dwnloadResult) {
                    console.log("Downloaded !" + dwnloadResult);
                    if (dwnloadResult == "true") {

                      IonicDeploy.extract(propertyCache.config.license + "-"+configData.appType, function (extractResult) {
                        if (extractResult == "done") {
                          console.log("Extracted successfully !" + extractResult);
                          sparkDataService.sendUpdateAcknowledgement().then(function (resp) {
                            $log.debug('Ack Success !', resp);

                            IonicDeploy.redirect(propertyCache.config.license+"-"+configData.appType, function () {
                              var checkInterval = $interval(function () {
                                LoadingMsg.hideLoading(id);
                                $interval.cancel(checkInterval);
                              }, 3000);
                            }, function () {
                              console.log("Redirected failed !");
                            });
                          }, function (err) {
                            $log.debug('ERR', err);
                          });
                        }
                      }, function (e) {
                        console.log("Extracted faliure !",e);
                      });

                    }
                  }, function (e) {
                    console.log("Download failed !",e);
                  });

              /*  } else {
                  console.log('You are not sure');
                }
              });
*/
            } else {
              /*LoadingMsg.hideLoading(updateMessageWindow);*/
              if(showMsg){
                var alertPopup = $ionicPopup.alert({
                  title: $filter('translate')('Info'),
                  template: '<div class="nf-center nf-valign-wrapper">' +
                  '<ion-spinner icon="ripple" class="nf-text-white"></ion-spinner>' +
                  '<span>{{"NoUpdates" | translate}}</span></div>'
                });
              }
            }
          }, function () {
            console.log("Check failed !");
          });

        }
      }

    };

  }]);


