/**
 * Created by shadeeka on 12/4/15.
 */
angular.module('app.controllers')
  .controller('StartDataCtrl', function ($scope, $state, $ionicPlatform, $log, $cordovaFile, $timeout, $cordovaFileTransfer, ionicMaterialInk, ionicMaterialMotion, eventProtocol,
                                         dataPersistenceService, sparkDataService, propertyCache, $ionicPopup, ModalViews, $ionicLoading, preConditions, issuesCache, $q, $http, auditProtocol, $rootScope) {
    ionicMaterialInk.displayEffect();
    var _self = this;
    _self.viewName = "linesettings";
    this.cache;
    _self.titleKey1 = "";
    _self.titleKey2 = "";
    _self.titleKey3 = "";
    _self.titleKey4 = "";
    _self.titleKey5 = "";
    _self.titleKey6 = "";
    _self.styleBefore = "";
    _self.soBefore = "";
    _self.liBefore = "";
    _self.sessionPlanBefore = "";
    _self.silhouetteBefore = "";

    _self.isInitialized = false;

    _self.isOperations = true;
    _self.isStyles = true;
    _self.isMembers = true;
    _self.whole = 0;
    _self.decimal = 0;
    $scope.incrementDisabled = false;
    $scope.decrementDisabled = false;
    _self.showDecimalVal = true;
    _self.showHelpers = false;
    _self.showOperators = true;
    _self.showMemberSpinner = false;
    _self.showbuyerData = false;


    _self.isDayStarted = false;
    _self.isDisabled = false;

    _self.day_start_prams = {
      sessionPlan: "",
      style: "",
      key1: "", // considers as the li
      key2: "",// considers as the so
      members: 18.0,
      siluhoutteid: "",
      operators: 0,
      helpers: 0,
      buyerId: "",
      categoryId: "",
      sizeId: "DEFAULT"
    };

    _self.cached_params = {
      sessionPlan: "",
      style: "",
      key1: "", // considers as the li
      key2: "",// considers as the so
      members: 0.0,
      siluhoutteid: "",
      operators: 0,
      helpers: 0,
      buyerId: "",
      categoryId: "",
      sizeId: "DEFAULT"
    };

    _self.sessionsPlans = [];
    _self.selected_plan = "";
    _self.siluhouttes = [];
    _self.planedStyles = [];
    _self.pos = [];
    _self.colours = [];
    _self.buyers = [];
    _self.sizeCats = [];
    _self.sizeList = [];

    _self.initData = function () {
      sparkDataService.getStyles().then(function (res) {
        preConditions.loadDayStartData();
      });
      console.log("Loding the Data ....!");

      angular.forEach(propertyCache.day_start, function (value, key) {
        if (_self.day_start_prams.hasOwnProperty(key)) {
          if (value != "") {
            _self.day_start_prams[key] = value;
            _self.isDayStarted = true;
          }
        }
      });

      angular.forEach(propertyCache.optional_day_start_data, function (value, key) {
        if (_self.day_start_prams.hasOwnProperty(key)) {
          if (value != "") {
            _self.day_start_prams[key] = value;
            _self.isDayStarted = true;
          }
        }
      });

      _self.loadPlanningData();

      if (localStorage.getItem("today-daystart") != null && localStorage.getItem("today-daystart")) {
        _self.cached_params = angular.copy(_self.day_start_prams);
      }

      _self.sessionsPlans = propertyCache.plans.sessionsPlans;

      _self.siluhouttes = propertyCache.siluhouttes.silihoutteNames;

      _self.planedStyles = propertyCache.planedStyles.styleNames;

      _self.pos = propertyCache.pos.poNames;

      _self.colours = propertyCache.colours.colorCodes;

      _self.sizelists = JSON.parse(localStorage.getItem("sizeList"));
      if (_self.sizelists) {
        for (var i = 0; i < _self.sizelists.length; i++) {
          _self.obj = _self.sizelists[i];
          if ($.inArray(_self.obj.buyerId, _self.buyers) == -1) {
            _self.buyers.push(_self.obj.buyerId);
          }
        }
      }

      if (propertyCache.factoryConfigs.helper_capturing == "true") {
        _self.showHelpers = true;
      } else {
        _self.showHelpers = false;
      }

      if (propertyCache.factoryConfigs.operator_capturing == "true") {
        _self.showOperators = true;
      } else {
        _self.showOperators = false;
      }

      if (propertyCache.factoryConfigs.member_capture == "true") {
        _self.showMemberSpinner = true;
      } else {
        _self.showMemberSpinner = false;
      }

      if(propertyCache.factoryConfigs.bulk_capturing == "true") {
        _self.showbuyerData = true;
      }else {
        _self.showbuyerData = false;
      }

      if (_self.showDecimalVal) {
        var str = _self.day_start_prams.members.toString();
        var numarray = str.split('.');
        if (numarray.length) {
          _self.whole = parseInt(numarray[0]);
          if (numarray[1])
            _self.decimal = parseInt(numarray[1]);
        } else {
          _self.whole = 0;
          _self.decimal = 0;
        }
      } else if (_self.showHelpers && _self.showOperators) {
        _self.decimal = _self.day_start_prams.helpers;
        _self.whole = _self.day_start_prams.operators;
      } else if (!_self.showOperators) {
        _self.whole = _self.day_start_prams.members;
      }


      if (configData.factoryType == "type1") {//aitc ,leisureline //>>defect rework
        _self.showDecimalVal = true;
        _self.title = 'Select a LI Code';
        _self.titleKey2 = "SO";
        _self.titleKey1 = "LI";
        _self.titleKey3 = "Style";
        _self.titleKey4 = "Buyer";
        _self.titleKey5 = "Cate.Id";
        _self.titleKey6 = "Size";
      } else if (configData.factoryType == "type2") {//intimo,nvs,csm >> rework regood
        _self.showDecimalVal = false;
        _self.title = 'Select an Colour Code';
        _self.titleKey2 = "PO";
        _self.titleKey1 = "Color";
        _self.titleKey3 = "Style";
        _self.titleKey4 = "Buyer";
        _self.titleKey5 = "Cate.Id";
        _self.titleKey6 = "Size";
      } else if (configData.factoryType == "type3") { //>>defect rework
        _self.showDecimalVal = false;
        _self.title = 'Select a LI Code';
        _self.titleKey2 = "SO";
        _self.titleKey1 = "LI";
        _self.titleKey3 = "Style";
        _self.titleKey4 = "Buyer";
        _self.titleKey5 = "Cate.Id";
        _self.titleKey6 = "Size";
      } else if (configData.factoryType == "type4") {//ama //>>defect rework
        _self.showDecimalVal = true;
        _self.title = 'Select an Item Code';
        _self.titleKey2 = "PO";
        _self.titleKey1 = "Item";
        _self.titleKey3 = "Style";
        _self.titleKey4 = "Buyer";
        _self.titleKey5 = "Cate.Id";
        _self.titleKey6 = "Size";
      } else if (configData.factoryType == "type5") {//>>defect rework
        _self.showDecimalVal = true;
        _self.title = 'Select an Colour Code';
        _self.titleKey2 = "PO";
        _self.titleKey1 = "Color";
        _self.titleKey1 = "Style";
        _self.titleKey4 = "Buyer";
        _self.titleKey5 = "Cate.Id";
        _self.titleKey6 = "Size";
      } else if (configData.factoryType == "type6") {//>>defect rework
        _self.showDecimalVal = false;
        _self.title = 'Select an Item Code';
        _self.titleKey2 = "PO";
        _self.titleKey1 = "Item";
        _self.titleKey3 = "Style";
        _self.titleKey4 = "Buyer";
        _self.titleKey5 = "Cate.Id";
        _self.titleKey6 = "Size";
      } else if (configData.factoryType == "type7") {//>>defect rework
        _self.showDecimalVal = false;
        _self.title = 'Select an Colour Code';
        _self.titleKey2 = "PO";
        _self.titleKey1 = "Color";
        _self.titleKey3 = "Style";
        _self.titleKey4 = "Buyer";
        _self.titleKey5 = "Cate.Id";
        _self.titleKey6 = "Size";
      } else if (configData.factoryType == "type8") {//>>defect rework day start lable interchange
        _self.showDecimalVal = false;
        _self.title = 'Select an Colour Code';
        _self.titleKey2 = "Style";
        _self.titleKey1 = "Color";
        _self.titleKey3 = "PO";
        _self.titleKey4 = "Buyer";
        _self.titleKey5 = "Cate.Id";
        _self.titleKey6 = "Size";
      } else if (configData.factoryType == "type9") {//>> Impress Rwotogood -> Rectified
        _self.showDecimalVal = false;
        _self.title = 'Select an Colour Code';
        _self.titleKey2 = "PO";
        _self.titleKey1 = "Color";
        _self.titleKey3 = "Style";
        _self.titleKey4 = "Buyer";
        _self.titleKey5 = "Cate.Id";
        _self.titleKey6 = "Size";

      } else {//default //>>defect rework
        _self.showDecimalVal = false;
        _self.title = 'Select a LI Code';
        _self.titleKey2 = "SO";
        _self.titleKey1 = "LI";
        _self.titleKey3 = "Style";
        _self.titleKey4 = "Buyer";
        _self.titleKey5 = "Cate.Id";
        _self.titleKey6 = "Size";
      }


      _self.updateSoLiOnEnter();

      $scope.$apply();

      /////////////////end of the method/////////////////////////////
    };

    //$ionicPlatform.ready(function () {
    //  _self.isInitialized = true;
    //});

    _self.watchObjects = function () {

      for (var key in _self.day_start_prams) {
        if (_self.cached_params.hasOwnProperty(key)) {
          if (_self.day_start_prams[key] != _self.cached_params[key]) {
            console.log(_self.day_start_prams[key] + " != " + _self.cached_params[key]);
            switch (key) {
              case 'sessionPlan' :
                _self.isOperations = true;
                break;
              case 'style' :
                _self.isStyles = true;
                break;
              case 'key1' :
                _self.isStyles = true;
                break;
              case 'key2' :
                _self.isStyles = true;
                break;
              case 'members' :
                _self.isMembers = true;
                break;
              case 'siluhoutteid' :
                _self.isStyles = true;
                break;
              case 'operators' :
                _self.isMembers = true;
                break;
              case 'helpers' :
                _self.isMembers = true;
                break;
            }
          }
        }
      }

    }


    _self.saveAndSendToServer = function () {

      if (!preConditions.getDayStartAvailable() || !_self.isDayStarted) {
        _self.isOperations = true;
        _self.isStyles = true;
        _self.isMembers = true;
      }
        _self.saveOperations();
        _self.saveStyles();
        if(propertyCache.factoryConfigs.member_capture == "true"){
          _self.saveMembers();
        }

    }

    _self.saveMembers = function () {

      var $event = eventProtocol.getEvent('members');

      $event.data.members = parseFloat(_self.day_start_prams['members'], 10);

      var data = new Object();
      data.date = $event.date;
      data.key = 'members';
      if(propertyCache.factoryConfigs.member_capture == "true"){
        data.value = _self.day_start_prams['members'];
      }else {
        data.value = 0;
      }
      dataPersistenceService.insertDayStart(data);

      propertyCache.setDayStart(_self.day_start_prams);
      if(propertyCache.factoryConfigs.bulk_capturing){
        propertyCache.setOptionalDayStart(_self.day_start_prams);
      }
      //send to the server
      sparkDataService.sendDataToServer($event);

      //////////////////audit//////////////////////
      var $audit = auditProtocol.getEvent("members");
      $audit.data.reference.members = _self.day_start_prams['members']
      sparkDataService.sendDataToServer($audit)
      /////////////////////////////////////////////////

    }

    _self.saveStyles = function () {
      var $event = eventProtocol.getEvent('styles');

      $event.data.so = _self.day_start_prams['key2'];
      $event.data.li = _self.day_start_prams['key1'];
      $event.data.style = _self.day_start_prams['style'];
      $event.data.siluhoutteid = _self.day_start_prams['siluhoutteid'];
      $event.data.startdatetime = new Date().getTime();
      if(propertyCache.factoryConfigs.bulk_capturing){
        $event.data.buyerId = _self.day_start_prams['buyerId'];
        $event.data.categoryId = _self.day_start_prams['categoryId'];
        $event.data.sizeId = _self.day_start_prams['sizeId'];
      }

      var data = new Object();
      data.date = $event.date;
      data.key = 'key1';
      data.value = _self.day_start_prams['key1'];
      dataPersistenceService.insertDayStart(data);

      var data = new Object();
      data.date = $event.date;
      data.key = 'key2';
      data.value = _self.day_start_prams['key2'];
      dataPersistenceService.insertDayStart(data);

      var data = new Object();
      data.date = $event.date;
      data.key = 'style';
      data.value = _self.day_start_prams['style'];
      dataPersistenceService.insertDayStart(data);

      var data = new Object();
      data.date = $event.date;
      data.key = 'siluhoutteid';
      data.value = _self.day_start_prams['siluhoutteid'];
      dataPersistenceService.insertDayStart(data);

      if(propertyCache.factoryConfigs.bulk_capturing) {
        var data = new Object();
        data.date = $event.date;
        data.key = 'buyerId';
        data.value = _self.day_start_prams['buyerId'];
        dataPersistenceService.insertDayStart(data);

        var data = new Object();
        data.date = $event.date;
        data.key = 'categoryId';
        data.value = _self.day_start_prams['categoryId'];
        dataPersistenceService.insertDayStart(data);

        var data = new Object();
        data.date = $event.date;
        data.key = 'sizeId';
        data.value = _self.day_start_prams['sizeId'];
        dataPersistenceService.insertDayStart(data);
      }

      propertyCache.setDayStart(_self.day_start_prams);
      if(propertyCache.factoryConfigs.bulk_capturing){
        propertyCache.setOptionalDayStart(_self.day_start_prams);
      }

      //send to the server
      sparkDataService.sendDataToServer($event);

      //////////////////audit//////////////////////
      var $audit = auditProtocol.getEvent("styles");
      $audit.data.reference.so = _self.day_start_prams['key2'];
      $audit.data.reference.li = _self.day_start_prams['key1'];
      $audit.data.reference.style = _self.day_start_prams['style'];
      $audit.data.reference.siluhoutteid = _self.day_start_prams['siluhoutteid'];
      if(propertyCache.factoryConfigs.bulk_capturing) {
        $audit.data.reference.buyerId = _self.day_start_prams['buyerId'];
        $audit.data.reference.categoryId = _self.day_start_prams['categoryId'];
        $audit.data.reference.sizeId = _self.day_start_prams['sizeId'];
      }
      sparkDataService.sendDataToServer($audit)
      /////////////////////////////////////////////////

      issuesCache.loadOperations();

      //get operation list for selected style
      sparkDataService.getOperationsForStyles(_self.day_start_prams['style']);

      propertyCache.setSelectedStyles(_self.day_start_prams['style']);
    }

    _self.saveOperations = function () {

      // this is because the date format declared in the mappings in ES have to come into terms with DA.
      var d = new Date();
      var month = '' + (d.getMonth() + 1);
      var day = '' + d.getDate();
      var year = d.getFullYear();

      if (month.length < 2)
        month = '0' + month;
      if (day.length < 2)
        day = '0' + day;
      var currentDate = year + "-" + month + "-" + day;

      var $event = eventProtocol.getEvent('operations');
      //set session plan
      $event.data.plandate = currentDate;
      $event.data.sessionplanname = _self.day_start_prams['sessionPlan'];

      var data = new Object();
      data.date = $event.date;
      data.key = 'sessionPlan';
      data.value = _self.day_start_prams['sessionPlan'];
      dataPersistenceService.insertDayStart(data);

      propertyCache.setDayStart(_self.day_start_prams);
      if(propertyCache.factoryConfigs.bulk_capturing){
        propertyCache.setOptionalDayStart(_self.day_start_prams);
      }

      //send to the server
      sparkDataService.sendDataToServer($event);

      //////////////////audit//////////////////////
      var $audit = auditProtocol.getEvent("operations");
      $audit.data.reference.sessionPlan = _self.day_start_prams['sessionPlan'];
      sparkDataService.sendDataToServer($audit)
      /////////////////////////////////////////////////
    }

    // Triggered on a button click, or some other target
    _self.showPopup = function () {
      _self.sessionPlanBefore = _self.day_start_prams.sessionPlan;
      $scope.selected = {};
      // An elaborate, custom popup
      var planPopup = $ionicPopup.show({
        template: '<ion-list><ion-radio ng-repeat="plan in startdatactrl.sessionsPlans" ng-model="startdatactrl.day_start_prams.sessionPlan" ng-value=" \'{{plan}}\' "> ' +
        '<div class="item item-text-wrap">{{plan}}</div> </ion-radio> </ion-list>',
        title: 'Select a plan',
        cssClass: "custom-popup",
        scope: $scope,
        buttons: [
          {text: 'Cancel'},
          {
            text: '<b>Done</b>',
            type: 'button-positive',
            onTap: function (e) {
              if (!_self.day_start_prams.sessionPlan) {
                //don't allow the user to close unless he enters wifi password
                e.preventDefault();
              } else {
                return _self.day_start_prams.sessionPlan;
              }
            }
          }
        ]
      });

      planPopup.then(function (res) {
        if (res) {
          _self.day_start_prams.sessionPlan = res;
        } else {
          _self.day_start_prams.sessionPlan = _self.sessionPlanBefore;
        }
      });
    };

    _self.showSiluhoutteIdPopup = function () {
      _self.silhouetteBefore = _self.day_start_prams.siluhoutteid;
      $scope.selected = {};
      // An elaborate, custom popup
      var planPopup = $ionicPopup.show({
        template: '<ion-list><ion-radio ng-repeat="siluhoutte in startdatactrl.siluhouttes" ng-model="startdatactrl.day_start_prams.siluhoutteid" ng-value=" \'{{siluhoutte}}\' "> ' +
        '<div class="item item-text-wrap">{{siluhoutte}}</div> </ion-radio> </ion-list>',
        title: 'Select a Siluhoutte',
        cssClass: "custom-popup",
        scope: $scope,
        buttons: [
          {text: 'Cancel'},
          {
            text: '<b>Done</b>',
            type: 'button-positive',
            onTap: function (e) {
              if (!_self.day_start_prams.siluhoutteid) {
                //don't allow the user to close unless he enters wifi password
                e.preventDefault();
              } else {
                return _self.day_start_prams.siluhoutteid;
              }
            }
          }
        ]
      });

      planPopup.then(function (res) {
        if (res) {
          _self.day_start_prams.siluhoutteid = res;
        } else {
          _self.day_start_prams.siluhoutteid = _self.silhouetteBefore;
        }
      });
    };

    _self.showStylePopup = function () {
      _self.styleBefore = _self.day_start_prams.style;
      $scope.selectedStyle = {};
      // An elaborate, custom popup
      var planPopup = $ionicPopup.show({
        template: '<ion-list><ion-radio ng-repeat="style in startdatactrl.planedStyles" ng-model="startdatactrl.day_start_prams.style" ng-value=" \'{{style}}\' "> ' +
        '<div class="item item-text-wrap">{{style}}</div> </ion-radio> </ion-list>',
        title: 'Select a Style',
        cssClass: "custom-popup",
        scope: $scope,
        buttons: [
          {text: 'Cancel'},
          {
            text: '<b>Done</b>',
            type: 'button-positive',
            onTap: function (e) {
              if (!_self.day_start_prams.style) {
                //don't allow the user to close unless he enters wifi password
                e.preventDefault();
              } else {
                _self.day_start_prams.key1 = "";
                _self.day_start_prams.key2 = "";
                dataPersistenceService.selectColoursPos(_self.day_start_prams.style).then(function (result) {
                  console.log("RESULTTTTTTTTTTTTTT -----> ", result);
                  self.pos = [];
                  self.colours = [];
                  for (var i = 0; i < result.rows.length; i++) {
                    if ($.inArray(result.rows.item(i).Po, self.pos) == -1) {
                      self.pos.push(result.rows.item(i).Po);
                    }
                    if ($.inArray(result.rows.item(i).Colour, self.colours) == -1) {
                      self.colours.push(result.rows.item(i).Colour);
                    }
                  }
                  _self.pos = self.pos;
                  _self.colours = self.colours;


                });
                return _self.day_start_prams.style;
              }
            }
          }
        ]
      });

      planPopup.then(function (res) {
        if (res) {
          _self.day_start_prams.style = res;
          //select silhouette here
          for (var key in _self.siluhouttes) {
            var nameArray = _self.siluhouttes[key].split("_");
            if (nameArray.length > 1) {
              var style = nameArray[0];
              if (_self.day_start_prams.style == style) {
                _self.day_start_prams.siluhoutteid = _self.siluhouttes[key];
              }
            }
          }
        } else {
          _self.day_start_prams.style = _self.styleBefore;
        }
      });
    };

    _self.showPoPopup = function () {
      _self.soBefore = _self.day_start_prams.key2;
      $scope.selectedPo = {};
      // An elaborate, custom popup
      var planPopup = $ionicPopup.show({
        template: '<ion-list><ion-radio ng-repeat="key2 in startdatactrl.pos" ng-model="startdatactrl.day_start_prams.key2" ng-value=" \'{{key2}}\' "> ' +
        '<div class="item item-text-wrap">{{key2}}</div> </ion-radio> </ion-list>',
        title: 'Select a PO no',
        cssClass: "custom-popup",
        scope: $scope,
        buttons: [
          {text: 'Cancel'},
          {
            text: '<b>Done</b>',
            type: 'button-positive',
            onTap: function (e) {
              if (!_self.day_start_prams.key2) {
                //don't allow the user to close unless he enters wifi password
                e.preventDefault();
              } else {
                _self.day_start_prams.key1 = "";
                //_self.cached_params.key2 = "";
                dataPersistenceService.selectColoursStyles(_self.day_start_prams.key2).then(function (result) {
                  console.log("RESULTTTTTTTTTTTTTT -----> ", result);
                  self.styles = [];
                  self.colours = [];
                  for (var i = 0; i < result.rows.length; i++) {
                    if(result.rows.item(i).Style == _self.day_start_prams.style){
                      if ($.inArray(result.rows.item(i).Colour, self.colours) == -1) {
                        self.colours.push(result.rows.item(i).Colour);
                      }
                    }
                    if ($.inArray(result.rows.item(i).Style, self.styles) == -1) {
                      self.styles.push(result.rows.item(i).Style);
                    }
                  }
                  _self.styles = self.styles;
                  _self.colours = self.colours;


                });
                return _self.day_start_prams.key2;
              }
            }
          }
        ]
      });

      planPopup.then(function (res) {
        if (res) {
          _self.day_start_prams.key2 = res;
        } else {
          _self.day_start_prams.key2 = _self.soBefore;
        }
      });
    };


    _self.showColourPopup = function () {
      _self.liBefore = _self.day_start_prams.key1;
      $scope.selectedColour = {};
      // An elaborate, custom popup
      var planPopup = $ionicPopup.show({
        template: '<ion-list><ion-radio ng-repeat="key1 in startdatactrl.colours" ng-model="startdatactrl.day_start_prams.key1" ng-value=" \'{{key1}}\' "> ' +
        '<div class="item item-text-wrap">{{key1}}</div> </ion-radio> </ion-list>',
        title: _self.title,
        cssClass: "custom-popup",
        scope: $scope,
        buttons: [
          {text: 'Cancel'},
          {
            text: '<b>Done</b>',
            type: 'button-positive',
            onTap: function (e) {
              if (!_self.day_start_prams.key1) {
                //don't allow the user to close unless he enters wifi password
                e.preventDefault();
              } else {
                dataPersistenceService.selectStylesPos(_self.day_start_prams.key1).then(function (result) {
                  console.log("RESULTTTTTTTTTTTTTT -----> ", result);
                  self.styles = [];
                  self.pos = [];
                  for (var i = 0; i < result.rows.length; i++) {
                    if ($.inArray(result.rows.item(i).Po, self.pos) == -1) {
                      self.pos.push(result.rows.item(i).Po);
                    }
                    if ($.inArray(result.rows.item(i).Style, self.styles) == -1) {
                      self.styles.push(result.rows.item(i).Style);
                    }
                  }
                  _self.styles = self.styles;
                  _self.pos = self.pos;


                });
                return _self.day_start_prams.key1;
              }
            }
          }
        ]
      });

      planPopup.then(function (res) {
        if (res) {
          _self.day_start_prams.key1 = res;
        } else {
          _self.day_start_prams.key1 = _self.liBefore;
        }
      });
    };

    _self.showBuyerPopup = function () {
      _self.buyerIdBeforeChange = _self.day_start_prams.buyerId;
      $scope.selected = {};
      // An elaborate, custom popup
      var planPopup = $ionicPopup.show({
        template: '<ion-list><ion-radio ng-repeat="buyer in startdatactrl.buyers" ng-model="startdatactrl.day_start_prams.buyerId" ng-value=" \'{{buyer}}\' "> ' +
        '<div class="item item-text-wrap">{{buyer}}</div> </ion-radio> </ion-list>',
        title: 'Select a Buyer',
        cssClass: "custom-popup",
        scope: $scope,
        buttons: [
          {text: 'Cancel'},
          {
            text: '<b>Done</b>',
            type: 'button-positive',
            onTap: function (e) {
              if (!_self.day_start_prams.buyerId) {
                //don't allow the user to close unless he enters wifi password
                e.preventDefault();
              } else {
                _self.sizeCats = [];
                _self.sizeCats.length = 0;
                if (_self.sizelists) {
                  for (var i = 0; i < _self.sizelists.length; i++) {
                    _self.obj = _self.sizelists[i];
                    if (_self.obj.buyerId == _self.day_start_prams.buyerId) {
                      if ($.inArray(_self.obj.categoryId, _self.sizeCats) == -1) {
                        _self.sizeCats.push(_self.obj.categoryId);
                      }
                    }
                  }
                }

                return _self.day_start_prams.buyerId;
              }
            }
          }
        ]
      });

      planPopup.then(function (res) {
        if (res) {
          _self.day_start_prams.buyerId = res;
          if(!_self.showMemberSpinner){
            _self.isDisabled = false;
          }
        } else {
          _self.day_start_prams.buyerId = _self.buyerIdBeforeChange;
        }
      });
    };

    _self.showCategoryPopup = function () {
      _self.categoryIdBeforeChange = _self.day_start_prams.categoryId;
      $scope.selected = {};
      // An elaborate, custom popup
      var planPopup = $ionicPopup.show({
        template: '<ion-list><ion-radio ng-repeat="category in startdatactrl.sizeCats" ng-model="startdatactrl.day_start_prams.categoryId" ng-value=" \'{{category}}\' "> ' +
        '<div class="item item-text-wrap">{{category}}</div> </ion-radio> </ion-list>',
        title: 'Select a Category',
        cssClass: "custom-popup",
        scope: $scope,
        buttons: [
          {text: 'Cancel'},
          {
            text: '<b>Done</b>',
            type: 'button-positive',
            onTap: function (e) {
              if (!_self.day_start_prams.categoryId) {
                //don't allow the user to close unless he enters wifi password
                e.preventDefault();
              } else {

                if (_self.sizelists) {
                  for (var i = 0; i < _self.sizelists.length; i++) {
                    _self.obj = _self.sizelists[i];
                    if (_self.obj.buyerId == _self.day_start_prams.buyerId && _self.obj.categoryId == _self.day_start_prams.categoryId) {
                      _self.sizeList = [];
                      _self.sizeList.length = 0;
                      _self.dataList = _self.obj.dataList;
                      for (var ii = 0; ii < _self.dataList.length; ii++) {
                        _self.dataOb = _self.dataList[ii];
                        if ($.inArray(_self.dataOb.sizeId, _self.sizeList) == -1) {
                          _self.sizeList.push(_self.dataOb.sizeId);
                        }
                      }
                    }
                  }
                }

                return _self.day_start_prams.categoryId;
              }
            }
          }
        ]
      });

      planPopup.then(function (res) {
        if (res) {
          _self.day_start_prams.categoryId = res;
          if(!_self.showMemberSpinner){
            _self.isDisabled = false;
          }
        } else {
          _self.day_start_prams.categoryId = _self.categoryIdBeforeChange;
        }
      });
    };

    _self.showSizePopup = function () {
      _self.sizeIdBeforeChange = _self.day_start_prams.sizeId;
      $scope.selected = {};
      // An elaborate, custom popup
      var planPopup = $ionicPopup.show({
        template: '<ion-list><ion-radio ng-repeat="size in startdatactrl.sizeList" ng-model="startdatactrl.day_start_prams.sizeId" ng-value=" \'{{size}}\' "> ' +
        '<div class="item item-text-wrap">{{size}}</div> </ion-radio> </ion-list>',
        title: 'Select a Size',
        cssClass: "custom-popup",
        scope: $scope,
        buttons: [
          {text: 'Cancel'},
          {
            text: '<b>Done</b>',
            type: 'button-positive',
            onTap: function (e) {
              if (!_self.day_start_prams.sizeId) {
                //don't allow the user to close unless he enters wifi password
                e.preventDefault();
              } else {
                return _self.day_start_prams.sizeId;
              }
            }
          }
        ]
      });

      planPopup.then(function (res) {
        if (res) {
          _self.day_start_prams.sizeId = res;
          if(!_self.showMemberSpinner){
            _self.isDisabled = false;
          }
        } else {
          _self.day_start_prams.sizeId = _self.sizeIdBeforeChange;
        }
      });
    };

    _self.setMembers = function () {
      var val = 0;
      var helpers = 0;
      if (!_self.showHelpers) {
        val = _self.whole.toString();
      } else if (_self.showHelpers && _self.showOperators) {
        var ratio = 0.0;
        // ratio = _self.decimal / _self.whole;
        // helpers = _self.decimal * ratio;
        val = parseFloat(_self.whole) + parseFloat(_self.decimal);
        _self.day_start_prams.operators = parseFloat(_self.whole);
        _self.day_start_prams.helpers = parseFloat(_self.decimal);

      } else if (_self.showDecimalVal) {
        val = _self.whole.toString() + "." + _self.decimal.toString();
      }
      _self.day_start_prams.members = parseFloat(val);
    }

    _self.increment = function () {
      _self.whole++;
    }

    _self.decrement = function () {
      _self.whole--;
    }

    _self.incrementDecimal = function () {
      _self.decimal++;

    }
    _self.decrementDecimal = function () {
      _self.decimal--;

    }
    $scope.$watch(angular.bind(_self, function () {
      return _self.decimal;
    }), function (newVal, oldVal) {
      if (newVal)
        _self.setMembers();
    });
    $scope.$watch(angular.bind(_self, function () {
      return _self.whole;
    }), function (newVal, oldVal) {
      if (newVal)
        _self.setMembers();
    });

    var failedImages = []
    var successImages = []
    var ImageLocation

    var factory = propertyCache.config.factory
    var module = propertyCache.config.line
    var tenant = propertyCache.config.tenant
    var options = {'directory': 'upload'};
    document.addEventListener('deviceready', function () {
      ImageLocation = cordova.file.dataDirectory + '/silhouetteList/';
    });

    _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!
          }, function (error) { // Error

          }, function (progress) {

          });
      });
    }

    _self.checkImages = function () {
      var frontURI = ImageLocation + _self.day_start_prams.siluhoutteid + "_Front.svg"
      var backURI = ImageLocation + _self.day_start_prams.siluhoutteid + "_Back.svg"
      $cordovaFile.checkFile(ImageLocation, frontURI.split("/").pop())
        .then(function (success) {
          successImages.push(_self.day_start_prams.siluhoutteid + "_Front.svg")
        }, function (error) {
          failedImages.push(_self.day_start_prams.siluhoutteid + "_Front.svg")
          _self.downloadImages();
        });
      $cordovaFile.checkFile(ImageLocation, backURI.split("/").pop())
        .then(function (success) {
          successImages.push(_self.day_start_prams.siluhoutteid + "_Back.svg")
        }, function (error) {
          failedImages.push(_self.day_start_prams.siluhoutteid + "_Back.svg")
          _self.downloadImages();
        });
    };

    _self.click = function () {
      _self.isDisabled = true;
      _self.cache = propertyCache.config;
      _self.setMembers();//for last update
      //_self.watchObjects();

      if(propertyCache.factoryConfigs.bulk_capturing == "true") {

        if (_self.day_start_prams.sessionPlan != "" && _self.day_start_prams.key1 != "" && _self.day_start_prams.key2 != "" && _self.day_start_prams.members != "" && _self.day_start_prams.buyerId != "" && _self.day_start_prams.categoryId != "") {
          _self.saveAndSendToServer();

          //_self.isOperations = false;
          //_self.isStyles = false;
          //_self.isMembers = false;

          preConditions.setCache(true);

          $ionicLoading.show({
            template: '<div class="nf-center nf-valign-wrapper"><span>Successfully Started !</span></div>'
          });
          $timeout(function () {
            $ionicLoading.hide();
          }, 2000);
          //update cache to current changes here
          _self.cached_params = angular.copy(_self.day_start_prams);
          localStorage.setItem("today-daystart", true);
          _self.exit();
        } else {
          $ionicLoading.show({
            template: '<div class="nf-center nf-valign-wrapper"><span>Please enter valid details !</span></div>'
          });
          $timeout(function () {
            $ionicLoading.hide();
          }, 2000);
        }

      }else {

        if (_self.day_start_prams.sessionPlan != "" && _self.day_start_prams.key1 != "" && _self.day_start_prams.key2 != "" && _self.day_start_prams.members != "") {
          _self.saveAndSendToServer();

          //_self.isOperations = false;
          //_self.isStyles = false;
          //_self.isMembers = false;

          preConditions.setCache(true);

          $ionicLoading.show({
            template: '<div class="nf-center nf-valign-wrapper"><span>Successfully Started !</span></div>'
          });
          $timeout(function () {
            $ionicLoading.hide();
          }, 2000);
          //update cache to current changes here
          _self.cached_params = angular.copy(_self.day_start_prams);
          localStorage.setItem("today-daystart", true);
          _self.exit();
        } else {
          $ionicLoading.show({
            template: '<div class="nf-center nf-valign-wrapper"><span>Please enter valid details !</span></div>'
          });
          $timeout(function () {
            $ionicLoading.hide();
          }, 2000);
        }
      }


      _self.checkImages()
    }

    $scope.$on('modal.shown', function (modal) {
      _self.isDisabled = false;
      if (ModalViews.getView(_self.viewName).isShown())

        _self.initData();

    });

    //diable and enable plus minus buttons with the number of members
    $scope.$watch(angular.bind(this, function () {
      return this.day_start_prams.members;
    }), function (newNumberOfMembers, oldNumberOfMembers) {
      if (newNumberOfMembers > 99) {
        $scope.incrementDisabled = true;
        $scope.decrementDisabled = false;
      }
      else if (newNumberOfMembers < 1) {
        $scope.decrementDisabled = true;
        $scope.incrementDisabled = false;
      }
      else {
        $scope.decrementDisabled = false;
        $scope.incrementDisabled = false;
      }
    });

    _self.exit = function () {
      if (ModalViews.getView(_self.viewName)) {
        propertyCache.setDayStart(_self.cached_params);
        if(propertyCache.factoryConfigs.bulk_capturing){
          propertyCache.setOptionalDayStart(_self.cached_params);
        }
        ModalViews.getView(_self.viewName).hide();
      }
    }


    _self.loadPlanningData = function () {
      var deferred = $q.defer();
      var _self = this;
      $log.info("loadPlanningData  " + preConditions.getDayStartAvailable());
      if (!preConditions.getDayStartAvailable()) {
        $log.info("getting planning data from server  ");
        var factory = propertyCache.config.factory;
        var module = propertyCache.config.line;
        var tenant = propertyCache.config.tenant;

        var d = new Date();
        var month = '' + (d.getMonth() + 1);
        var day = '' + d.getDate();
        var year = d.getFullYear();

        if (month.length < 2)
          month = '0' + month;
        if (day.length < 2)
          day = '0' + day;
        var currentDate = year + "-" + month + "-" + day;

        var url = 'http://' + propertyCache.config.syncIp +
          '/dataman/getstyleinfo?tenant=' + tenant + '&factory=' + factory + '&line=' + module + "&date=" + currentDate;
        $http.get(url).then(function (response) {
          console.log("get plan data from server ----> " + response);
          deferred.resolve(response);
          var dataServer = response["data"];
          if (dataServer != "") {
            _self.day_start_prams["style"] = dataServer[0]["style"];
            _self.day_start_prams["key1"] = dataServer[0]["li"];
            _self.day_start_prams["key2"] = dataServer[0]["so"];
            _self.day_start_prams["siluhoutteid"] = dataServer[0]["siluhoutteid"];
            _self.day_start_prams["members"] = parseInt(dataServer[0]["members"]) || 18;
            _self.day_start_prams["sessionPlan"] = dataServer[0]["sessionPlan"];
            _self.day_start_prams["operators"] = dataServer[0]["operators"];
            _self.day_start_prams["helpers"] = dataServer[0]["helpers"];

            if (propertyCache.factoryConfigs.operator_capturing == "true") {
              _self.whole = dataServer[0]["operators"];
              _self.decimal = dataServer[0]["helpers"];
            } else {
              _self.whole = parseInt(dataServer[0]["members"]) || 18;
            }
          }
        }, function (err) {
          console.log('ERR', err);
          deferred.reject(err);
        })
      }
      return deferred.promise;
    }

    _self.updateSoLiOnEnter = function () {
      dataPersistenceService.selectColoursPos(_self.day_start_prams.style).then(function (result) {
        console.log("RESULTTTTTTTTTTTTTT -----> ", result);
        self.pos = [];
        self.colours = [];
        for (var i = 0; i < result.rows.length; i++) {
          if ($.inArray(result.rows.item(i).Po, self.pos) == -1) {
            self.pos.push(result.rows.item(i).Po);
          }
          if ($.inArray(result.rows.item(i).Colour, self.colours) == -1) {
            self.colours.push(result.rows.item(i).Colour);
          }
        }
        _self.pos = self.pos;
        _self.colours = self.colours;


      });
    }


    $rootScope.$on("update-line", function () {
        console.log('update-line occur ');
        _self.loadPlanningData().then(function (res) {
          preConditions.loadDayStartData();
        })
      }
    );

  });
