/**
 * Created by shadeeka on 1/10/16.
 */
angular.module('app.controllers')
  .controller('MeaslesCtrl', function ($scope, $timeout, $filter, dataPersistenceService, $ionicHistory, sparkDataService, $rootScope, undoOperation, $ionicLoading, $state, $stateParams, ionicMaterialInk, $ionicPopup, propertyCache, cacheViews, $log, $cordovaFile, $http, auditProtocol, $cordovaFileTransfer) {
    var ImageLocation = cordova.file.dataDirectory + '/silhouetteList/';
    //var ImageLocation = cordova.file.externalRootDirectory + '/silhouetteList/';
    var factory = propertyCache.config.factory
    var module = propertyCache.config.line
    var tenant = propertyCache.config.tenant
    var options = {'directory': 'upload'};

    var _self = this;
    $scope.browser = ionic.Platform.ua;
    $scope.sid = propertyCache.day_start.siluhoutteid;

    var frontURI = ImageLocation + $scope.sid + "_Front.svg"
    var backURI = ImageLocation + $scope.sid + "_Back.svg"

    _self.showImageFront= function() {
      $http.get(ImageLocation + $scope.sid + "_Front.svg")
        .then(function (img_front) {
          $scope.front = img_front.data
        }, function (error) {
          _self.checkImages();
        });

      setTimeout(function () {
        $ionicLoading.hide();
        $('#front_image').mapster(mapOptions);
      }, 2000);

    }

    _self.showImageBack= function() {
      $http.get(ImageLocation + $scope.sid + "_Back.svg")
        .then(function (img_back) {
          $scope.back = img_back.data
        }, function (error) {
          _self.checkImages();
      });


      setTimeout(function () {
        $ionicLoading.hide();
        $('#back_image').mapster(mapOptions);
      }, 2000);
    }

    try{
      _self.showImageFront()
      _self.showImageBack()
    }

    catch (e){
      // handle errors in processing or in error.
      console.log(e)
    }
    //$scope.front = ImageLocation + $scope.sid + "_Front.svg";
    //$scope.back = ImageLocation + $scope.sid + "_Back.svg";

//    $cordovaFile.checkFile(ImageLocation, frontURI.split("/").pop())
//      .then(function(success) {
//
//      }, function(error){
//        var alertPopup = $ionicPopup.alert({
//          title: 'Syncing Error',
//          template: '<div class="nf-center nf-valign-wrapper">' +
//          '<ion-spinner icon="ripple" class="nf-text-white"></ion-spinner>' +
//          '<span>Please Resync Silhouette Images</span></div>'
//        });
//        $state.go('app.home');
//        $ionicHistory.nextViewOptions({
//          disableBack: true
//        });
//})


    _self.actualHeight = 1;
    _self.actualWidth = 1;
    _self.measles = [];
    _self.activeCategory = {};
    _self.inprogress = false;
    // _self.preserveState=true;
    //image map options
    var mapOptions = {
      noHrefIsMask: false,
      mapKey: 'group',
      configTimeout: 20000,
      fillOpacity: 1,
      staticState: true,
      areas: []
    };
    _self.defect = {};

    _self.setDataState = function () {
      _self.defect = angular.copy(cacheViews.defect);
      $scope.categories = [];
      $scope.categories = angular.copy(_self.defect.data.issues);
      _self.activeCategory = $scope.categories[0];
      $scope.categories[0].selected = true;
      $scope.$safeApply($scope);

    }

    _self.init = function () {

      var numberOfGroups = 8; // get number of groups as component property

      var areaGroups = new Array();

      for (var i = 1; i <= numberOfGroups; i++) {
        var color = window.settings.cmap['' + i];
        color = window.settings.cmap['' + i].substr(1);

        var area = new Object();
        area.key = "group_" + i; //key to identify colors

        area.stroke = false;
        area.isSelectable = false;
        area.isDeselectable = false;
        area.fillColor = color;
        area.render_select = {fillColor: color};
        areaGroups.push(area);
      }

      mapOptions["areas"] = areaGroups;

      //setTimeout(function () {
      //  $('#front_image').mapster(mapOptions);
      //}, 2000);
      //setTimeout(function () {
      //  $('#back_image').mapster(mapOptions);
      //}, 2000);
    }
    _self.init();

    _self.selectCategory = function (cat) {

      _self.activeCategory.selected = false;
      _self.activeCategory = cat;
      cat.selected = true;

    }

    _self.tapFront = function (event) {

      if (!_self.activeCategory.category_id)
        return;

      //calculate position
      var cords = _self._calPositions(event, this);

      //save ratio into frontMeasles
      _self.measles.push({
        x: (cords.x / _self.actualWidth),
        y: (cords.y / _self.actualHeight),
        category: _self.activeCategory.category_id,
        image: "frontimage"
      });
      // _self.preserveState=true;
      _self.updateDataPointsFront();

    }
    _self.tapBack = function (event) {
      if (!_self.activeCategory.category_id)
        return;
      //calculate position
      var cords = _self._calPositions(event, this);
      //mark image
      //save ratio into backMeasles
      _self.measles.push({
        x: (cords.x / _self.actualWidth),
        y: (cords.y / _self.actualHeight),
        category: _self.activeCategory.category_id,
        image: "backimage"
      });
      // _self.preserveState=true;
      _self.updateDataPointsBack();
    }

    _self.refreshMap = function (image) {
      $('#' + image).mapster('unbind');
      $('#' + image).mapster('bind', mapOptions);
    }

    _self.updateDataPointsFront = function () {


      $("map[name*='front_map']").html('');
      var frontM = angular.copy($filter("filter")(_self.measles, {image: 'frontimage'}));
      angular.forEach(frontM, function (point) {

        var x = (point.x * _self.actualWidth);
        var y = (point.y * _self.actualHeight);
        $("map[name*='front_map']").append('<area shape="circle" group="group_' + point.category.charAt(0) + '" coords="' + x + ',' + y + ',20" href="#">');
      });
      $('#front_image').mapster('unbind');
      $('#front_image').mapster('bind', mapOptions);
      var images = $("#front_image").siblings("img.mapster_el");
      if (images.length >= 2) {
        images[0].remove();
      }
      var canvas = $("#front_image").siblings("canvas");
      if (canvas.length >= 4) {
        canvas[0].remove();
        canvas[1].remove();
      }
    }
    _self.updateDataPointsBack = function () {


      $("map[name*='back_map']").html('');
      var backM = angular.copy($filter("filter")(_self.measles, {image: 'backimage'}));
      angular.forEach(backM, function (bpoint) {

        var x = (bpoint.x * _self.actualWidth);
        var y = (bpoint.y * _self.actualHeight);
        $("map[name*='back_map']").append('<area shape="circle" group="group_' + bpoint.category.charAt(0) + '" coords="' + x + ',' + y + ',20" href="#">');
      });
      $('#back_image').mapster('unbind');
      $('#back_image').mapster('bind', mapOptions);

      var images = $("#back_image").siblings("img.mapster_el");
      if (images.length >= 2) {
        images[0].remove();
      }
      var canvas = $("#back_image").siblings("canvas");
      if (canvas.length >= 4) {
        canvas[0].remove();
        canvas[1].remove();
      }

    }
    $scope.getCords = function (dot) {
      return (dot.x * _self.actualWidth) + "," + (dot.y * _self.actualHeight) + ",20";
    }

    $scope.getGroup = function (dot) {
      return "group_" + dot.category.toString().charAt(0);
    }

    var elemF = document.getElementById('front_image');
    var elemB = document.getElementById('back_image');
    elemF.addEventListener('click', _self.tapFront, false);
    elemB.addEventListener('click', _self.tapBack, false);

    var dbg = document.getElementById('dbg');  //just for debug div instead of console

    _self._calPositions = function (e, element) {

      var m_posx = 0, m_posy = 0, e_posx = 0, e_posy = 0,
        obj = element;
      //get mouse position on document crossbrowser
      if (!e) {
        e = window.event;
      }
      if (e.pageX || e.pageY) {
        m_posx = e.pageX;
        m_posy = e.pageY;
      } else if (e.clientX || e.clientY) {
        m_posx = e.clientX + document.body.scrollLeft
        + document.documentElement.scrollLeft;
        m_posy = e.clientY + document.body.scrollTop
        + document.documentElement.scrollTop;
      }

      //get parent element position in document
      if (obj.offsetParent) {
        do {
          e_posx += obj.offsetLeft;
          e_posy += obj.offsetTop;
        } while (obj = obj.offsetParent);
      }
      // mouse position minus elm position is mouseposition relative to element:
      /* dbg.innerHTML = ' X Position: ' + (m_posx-e_posx)
       + ' Y Position: ' + (m_posy-e_posy);*/

      var x = m_posx - e_posx;
      var y = m_posy - e_posy;

      var targetElement = e.target;
      //store to do final calculation
      _self.actualHeight = targetElement.naturalHeight;
      _self.actualWidth = targetElement.naturalWidth;

      var xPosition = x * (targetElement.naturalWidth / targetElement.clientWidth);
      var yPosition = y * (targetElement.naturalHeight / targetElement.clientHeight);
      return {x: xPosition, y: yPosition};
    }

    _self.reset = function () {

    }

    _self.save = function () {
      if (!_self.measles.length)
        return;

      var issuesWithMeasles = _self._prepareData();
      _self.defect.data.issues = issuesWithMeasles;
      //set silhouette id
      _self.defect.data.siluhoutteid = $scope.sid;

      //      var cats = [];
      //var count = 0;
      //for(var i =0; i < issuesWithMeasles.length;i++){
      //  if(issuesWithMeasles[i].locations != null){
      //    count += issuesWithMeasles[i].locations.length;
      //    var catsForSingleDefect = issuesWithMeasles[i].locations;
      //    for(var j =0;j< catsForSingleDefect.length;j++){
      //      var categoryData = new Object();
      //      categoryData.date = _self.defect.date;
      //      categoryData.defect = catsForSingleDefect[j].category;
      //
      //      dataPersistenceService.insertDefectCategory(categoryData);
      //
      //      cats.push(catsForSingleDefect[j].category);
      //  }
      //  }
      //}

      $rootScope.$broadcast("modelCountUpdate", {type: "defects"});
      //send event to database
      dataPersistenceService.dailyCountPreProcess(_self.defect);

      //insert all defect categories
      var categoryData = new Object();
      categoryData.date = _self.defect.date;

      var cats = [];
      for (var j = 0; j < issuesWithMeasles.length; j++) {
        cats.push(issuesWithMeasles[j].category_id);
      }
      categoryData.defect = cats;
      dataPersistenceService.insertDefectCategory(categoryData);

      sparkDataService.sendDataToServer(_self.defect);

      ///////////////////audit//////////////////////
      var $audit = auditProtocol.getEvent('defects');
      $audit.data.reference.issues = _self.defect.data.issues;
      sparkDataService.sendDataToServer($audit)
      /////////////////////////////////////////////////

      var dataToUndoService = new Object();
      dataToUndoService.dataType = 'defects';
      dataToUndoService.jsonSent = _self.defect.data;
      dataToUndoService.defectList = cats;
      undoOperation.setLastEvent(dataToUndoService);

      console.log("Undo defect List ---------------------> ", dataToUndoService);

      $ionicHistory.nextViewOptions({
        disableBack: true
      });
      $state.go('app.home');
    };

    var failedImages = []
    var successImages = []

    _self.loadingPopUp = function (progress) {
      if(progress.total==0){
        progress.total=1;
      }
      $ionicLoading.show({
        template: '<div class="nf-center nf-valign-wrapper"><span>Downloading...Please wait...</span></div>'
      });
    };


    _self.downloadImages = function () {
      var trustHosts = true
      angular.forEach(failedImages, function (silihoutteName, key) {
        var index = failedImages.indexOf(silihoutteName);
        failedImages.splice(index, 1);
        //var url = "http://nfs-integration.eastus.cloudapp.azure.com:9000/assets/ionic/img/silhouettes/" + silihoutteName + ".svg";
        var url = 'http://' + propertyCache.config.syncIp + '/dataman/getsiluhoutteimage?tenant=' + tenant + '&factory=' + factory + '&siluhoutteName=' + silihoutteName;
        var filename = url.split("=").pop();
        var targetPath = ImageLocation + filename;

        $cordovaFileTransfer.download(url, targetPath, options, trustHosts)
          .then(function (success) { // Success!
            $ionicLoading.hide();
            _self.showImageBack()
            _self.showImageFront()

          }, function (error) { // Error
            $ionicPopup.alert({
              title: 'Syncing Error',
              template: '<div class="nf-center nf-valign-wrapper">' +
              '<ion-spinner icon="ripple" class="nf-text-white"></ion-spinner>' +
              '<span>Please Resync Silhouette Images</span></div>'
            });
            $ionicLoading.hide();
            $ionicHistory.nextViewOptions({
              disableBack: true
            });
            $state.go('app.home');
          }, function (progress) {
            _self.loadingPopUp(progress);
          });
      });
    }

    _self.checkForceDownload = function (){
      console.log("checkForceDownload ");
      if(document.getElementById('front_image').style.display=="none"){
        console.log("front image not showing began to download now ... ");
        failedImages.push($scope.sid+ "_Front.svg");
        _self.downloadImages();
      }
      if(document.getElementById('back_image').style.display=="none"){
        console.log("back image not showing began to download now ... ");
        failedImages.push($scope.sid+ "_Back.svg");
        _self.downloadImages();
      }
    }

    _self.checkImages = function () {
      $cordovaFile.checkFile(ImageLocation, frontURI.split("/").pop())
        .then(function (success) {
          _self.showImageFront()
          successImages.push($scope.sid+ "_Front.svg")
        }, function (error) {
          failedImages.push($scope.sid+ "_Front.svg")
          _self.downloadImages();
        });
      $cordovaFile.checkFile(ImageLocation, backURI.split("/").pop())
        .then(function (success) {
          _self.showImageBack()

          successImages.push($scope.sid+ "_Back.svg")
        }, function (error) {
          failedImages.push($scope.sid+ "_Back.svg")
          _self.downloadImages();
        });
    };


    $scope.$on('$ionicView.enter', function () {
      setTimeout(function () {
        _self.checkForceDownload();
      }, 500);
    });

    $scope.$on('$ionicView.beforeEnter', function () {
      $scope.$parent.clearAllFabs();
      _self.setDataState();
      _self.checkImages()
      //_self.downloadImages();

    });

    _self._prepareData = function () {
      var issues = angular.copy(_self.defect.data.issues);
      angular.forEach(_self.measles, function (item, itemIndex) {
        angular.forEach(issues, function (category, catIndex) {
          category.name = category.name;

          if (category.category_id == item.category) {
            if (category.locations) {
              category.locations.push(item);
            }
            else {
              category["locations"] = [];
              category.locations.push(item);
            }
          }
        });
      });
      return issues;
    }

    _self.undo = function () {
      var pop = _self.measles.pop();
      //$timeout(function () {
      if (pop.image == "frontimage") {
        _self.updateDataPointsFront();
      } else
        _self.updateDataPointsBack();
      // }, 100);

    }
    $scope.safeApply = function (fn) {
      var phase = this.$root.$$phase;
      if (phase == '$apply' || phase == '$digest') {
        if (fn && (typeof(fn) === 'function')) {
          fn();
        }
      } else {
        this.$apply(fn);
      }
    };
    //utill function
    $("img").error(function () {
      $(this).hide();
    });

  });
