/**
 * Created by shadeeka on 12/4/15.
 */
angular.module('app.controllers')
  .controller('ConfigCtrl', function ($scope, $state, $filter, ionicMaterialInk, $ionicPlatform, ionicMaterialMotion, $log, sparkDataService, dataPersistenceService, propertyCache, ModalViews, auditProtocol, $http, $q, $ionicPopup) {

    ionicMaterialInk.displayEffect();

    var _self = this;
    _self.viewName = "config";
    _self.tokenId = "";
    _self.config = {
      dataIp: configData.dataIp,
      syncIp: configData.syncIp,
      tenant: configData.tenant,
      factory: configData.factory,
      line: configData.line,
      defaultStyle: configData.defaultStyle,
      factoryType: configData.factoryType,
      operator_change: configData.operator_change,
      helper_capturing: configData.helper_capturing,
      operator_capturing: configData.operator_capturing,
      rwtogoodRectificationSteps: configData.rwtogoodRectificationSteps,
      bulk_capturing: configData.bulk_capturing,
      member_capture: configData.member_capture,
      size_wise_events: configData.size_wise_events,
      default_bundle_sizes: configData.default_bundle_sizes,
      license: configData.license
    };

    //get configurations if available from database
    _self.initConfig = function () {
      dataPersistenceService.selectConfigurations().then(function (result) {
        for (var i = 0; i < result.rows.length; i++) {
          if (_self.config.hasOwnProperty(result.rows.item(i).Key)) {
            $log.debug(result.rows.item(i).Key, result.rows.item(i).Value);
            _self.config[result.rows.item(i).Key] = result.rows.item(i).Value;
          }
        }

        //save data
        if (_self.config['dataIp'].trim() == "") {
          _self.click(false);
        }
      });
    }
    $ionicPlatform.ready(function () {
      _self.initConfig();
    });

    //save configuration data to database
    _self.click = function (buttonclick) {
      $log.info("saving config data " + buttonclick);
      var date = new Date();
      var day = date.getDate();
      var monthIndex = date.getMonth();
      var year = date.getFullYear();
      var today = year + '.' + monthIndex + '.' + day;

      for (var key in _self.config) {

        if (typeof(_self.config[key]) === "boolean" || typeof(_self.config[key] === "object")) {
          _self.config[key] = _self.config[key]
        } else {
          _self.config[key] = _self.config[key].trim();
        }

        if (_self.config.hasOwnProperty(key)) {
          var data = new Object();
          data.date = today;
          data.key = key;
          data.value = _self.config[key];
          if (typeof(_self.config[key]) === "boolean" || typeof(_self.config[key] === "object")) {
            dataPersistenceService.insertConfiguration(data);
          } else {
            if (_self.config[key].trim() != "") {
              dataPersistenceService.insertConfiguration(data);
            }
          }
        }
      }
      propertyCache.setConfig(_self.config);
      ///////////////////audit//////////////////////
      var $audit = auditProtocol.getEvent('configuration');
      $audit.data.reference.dataIp = configData.dataIp,
        $audit.data.reference.syncIp = configData.syncIp,
        $audit.data.reference.tenant = configData.tenant,
        $audit.data.reference.factory = configData.factory,
        sparkDataService.sendDataToServer($audit)
      /////////////////////////////////////////////////


      $http.get("http://"+propertyCache.config.syncIp+"/deploy/get/licenses?factory=" + _self.config.factory + "&tenant=" + _self.config.tenant + "&status=not-active&appType=qc_app&macAddress="+ propertyCache.macAddress).then(function (response) {
        $log.debug(response);

        var data = [];
        data = response['data'];

        if (data) {
          $log.debug("License Key ", data[0]);

          configData.license = data[0];
          _self.config.license = data[0];

          var data = new Object();
          data.date = today;
          data.key = "license";
          data.value = _self.config["license"];
          dataPersistenceService.insertConfiguration(data);

          $http.get("http://"+propertyCache.config.syncIp+"/deploy/update/license?factory=" + _self.config.factory + "&line=" + _self.config.line + "&status=not-active&appType=qc_app").then(function (response) {
            $log.debug("Updated !", response);
          }, function (err) {
            $log.debug("Update failed !", err);
          });

          if (buttonclick) {
            _self.exit();
          }

        } else {
          var alertPopup = $ionicPopup.alert({
            title: 'Invalid License Id !',
            template: '<div class="nf-center nf-valign-wrapper">' +
            '<ion-spinner icon="ripple" class="nf-text-white"></ion-spinner>' +
            '<span>Invalid License Id !</span></div>'
          });
        }


      }, function (err) {
        $log.debug('ERR', err);
        var alertPopup = $ionicPopup.alert({
          title: 'Invalid License Id !',
          template: '<div class="nf-center nf-valign-wrapper">' +
          '<ion-spinner icon="ripple" class="nf-text-white"></ion-spinner>' +
          '<span>Invalid License Id !</span></div>'
        });
        // deferred.reject(err);
      });




    }

    _self.clickRetrieve = function () {
      var token = _self.tokenId;
      var serverPart1 = token.split("-");
      var factory = "";
      var line = "";
      var serverType = "live";
      if (serverPart1.length > 1) {
        factory = serverPart1[0];
        serverType = serverPart1[1];
      } else {
        factory = serverPart1[0];
      }
      $log.info("clickRetrieve server data " + token);
      var deferred = $q.defer();
      var self = this;
      $http.get(configData.serverConfig + "/" + factory + ".json").then(function (response) {
        $log.debug("Config data ", response);
        var data = [];
        data = response['data'];
        if (data[factory] != undefined && data[factory].length > 0) {
          configData.dataIp = data[factory][0][serverType]['dataIp'] + ":" + data[factory][0][serverType]['dataPort'];
          configData.syncIp = data[factory][0][serverType]['syncIp'] + ":" + data[factory][0][serverType]['syncPort'];
          configData.tenant = data[factory][0][serverType]['tenant'];
          configData.factory = data[factory][0][serverType]['factory'];
          configData.defaultStyle = data[factory][0][serverType]['defaultStyle'];
          configData.factoryType = data[factory][0][serverType]['qcFactoryType'];
          configData.rwtogoodRectificationSteps = data[factory][0][serverType]['rwtogoodRectificationSteps'];
          configData.helper_capturing = data[factory][0][serverType]['helper_capturing'];
          configData.operator_capturing = data[factory][0][serverType]['operator_capturing'];
          configData.operator_change = data[factory][0][serverType]['operator_change'];
          configData.bulk_capturing = data[factory][0][serverType]['bulk_capturing'];
          configData.member_capture = data[factory][0][serverType]['member_capture'];
          configData.size_wise_events = data[factory][0][serverType]['size_wise_events'];
          configData.default_bundle_sizes = data[factory][0][serverType]['default_bundle_sizes'];

          _self.config.dataIp = configData.dataIp;
          _self.config.syncIp = configData.syncIp;
          _self.config.tenant = configData.tenant;
          _self.config.factory = configData.factory;
          _self.config.defaultStyle = configData.defaultStyle;
          _self.config.factoryType = configData.factoryType;
          _self.config.rwtogoodRectificationSteps = configData.rwtogoodRectificationSteps;
          _self.config.helper_capturing = configData.helper_capturing;
          _self.config.operator_capturing = configData.operator_capturing;
          _self.config.operator_change = configData.operator_change;
          _self.config.bulk_capturing = configData.bulk_capturing;
          _self.config.member_capture = configData.member_capture;
          _self.config.size_wise_events = configData.size_wise_events;
          _self.config.default_bundle_sizes = configData.default_bundle_sizes;

        } else {
          var alertPopup = $ionicPopup.alert({
            title: 'Invalid Token Id ',
            template: '<div class="nf-center nf-valign-wrapper">' +
            '<ion-spinner icon="ripple" class="nf-text-white"></ion-spinner>' +
            '<span>Please check token id</span></div>'
          });
        }
        deferred.resolve(response);
      }, function (err) {
        $log.debug('ERR', err);
        var alertPopup = $ionicPopup.alert({
          title: 'Invalid Token Id ',
          template: '<div class="nf-center nf-valign-wrapper">' +
          '<ion-spinner icon="ripple" class="nf-text-white"></ion-spinner>' +
          '<span>Please check token id</span></div>'
        });
        deferred.reject(err);
      });

      // $http.get("http://"+propertyCache.config.syncIp+"/deploy/get/licenses?factory=" + factory + "&tenant="+_self.config.tenant+"&status=not-active&appType=qc_app").then(function (response) {


      return deferred.promise;
    }

    //----------- Load rework items before view enter ----//

    $scope.$on('$ionicView.beforeEnter', function () {
      $scope.$parent.clearFabs();

    });
    _self.exit = function () {
      if (ModalViews.getView(_self.viewName)) {
        _self.initConfig();
        sparkDataService.syncAuthentication();
        ModalViews.getView(_self.viewName).hide();
      }
    }

    $scope.$on('modal.shown', function (modal) {
      if (ModalViews.getView(_self.viewName).isShown()) {
      }
      _self.initConfig();
    });

  });
