/**
 * Created by shadeeka on 12/4/15.
 */
angular.module('app.services')
  .filter('checkEmptyProps', function(){
    return function(object) {
      var visibleUser = true;
      for(var key in object) {
        if(object[key]== "" || object[key]==null) {
          visibleUser = false;
          break;
        }
      }
      return visibleUser;
    };
  })
// =========================================================================
// Event mediator service
// =========================================================================
  .factory('preConditions', ['$log','$http','$rootScope', '$state','$filter', 'dataPersistenceService','propertyCache','ModalViews', function ($log, $http,$rootScope, $state, $filter,dataPersistenceService,propertyCache,ModalViews) {

    var cache = {
      configAvailable: false,
      startDayAvailable: false
    };


    return {

      //check pre-conditions before proceed with the event
      checkPreValidations: function () {
        $log.debug("eventMediatorService : checkPreConditions :configs");
        this.loadSiluhouttes();
        this.loadDayStartData();
        this.isAvailableConfigurations();
        if(cache.configAvailable){
          $log.debug("Loading Start data !");
          this.isAvailableDayStart();
        }
      },

      getConfigData: function () {
        return cache;
      },
      getDayStartAvailable: function () {
        return cache.startDayAvailable;
      },
      setCache: function (data) {
        cache.startDayAvailable = data;
        $log.debug(cache);

      },
      loadSessionPlans : function () {
        $log.debug("Loading Session plans !");
        dataPersistenceService.selectSessionPlanNames().then(function (res) {
          self.sessionsPlans = [];
          for (var i = 0; i < res.rows.length; i++) {
            self.sessionsPlans.push(res.rows.item(i).Name);
          }
          propertyCache.plans.sessionsPlans = self.sessionsPlans;
        });
      },

      loadSiluhouttes : function(){
        $log.debug("Loading siluhouttes !");
        dataPersistenceService.selectSiluhouttes().then(function(result){
          self.siluhouttes =[];
          for(var i =0; i < result.rows.length ; i ++){
            self.siluhouttes.push(result.rows.item(i).Name);
          }
          propertyCache.siluhouttes.silihoutteNames = self.siluhouttes;
        })
      },

      loadDayStartData : function (){
        $log.debug("Loading Styles POs Colours !");
        dataPersistenceService.selectAllFromStyles_po_colours().then(function(result){
          self.styles =[];
          self.pos =[];
          self.colours =[];
          for(var i =0; i < result.rows.length ; i ++){
            for (var i = 0; i < result.rows.length; i++) {
              if($.inArray(result.rows.item(i).Style, self.styles) == -1){
                self.styles.push(result.rows.item(i).Style);
              }

              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);
              }
            }
          }
          propertyCache.planedStyles.styleNames = self.styles;
          propertyCache.pos.poNames = self.pos;
          propertyCache.colours.colorCodes = self.colours;
        })
      },

      isAvailableDayStart: function () {
        //check day start here

        if (cache.startDayAvailable) {
          $log.debug("Day Start is available");
          return true;
        }

        $log.debug("Checking if day start is available");
        //first check cache
        //if not in cache go to database and check and save in cache
        dataPersistenceService.selectDayStart().then(function (result) {
          $log.debug("Day Start result");
          $log.debug(result);

          for (var i = 0; i < result.rows.length; i++) {
            if(propertyCache.day_start.hasOwnProperty(result.rows.item(i).Key)){
              if(result.rows.item(i).Date == dataPersistenceService.getFormattedDate()) {
                $log.debug(result.rows.item(i).Key, result.rows.item(i).Value);
                propertyCache.day_start[result.rows.item(i).Key] = result.rows.item(i).Value;
              }
            }else if(propertyCache.optional_day_start_data.hasOwnProperty(result.rows.item(i).Key)){
              if(result.rows.item(i).Date == dataPersistenceService.getFormattedDate()) {
                $log.debug(result.rows.item(i).Key, result.rows.item(i).Value);
                propertyCache.optional_day_start_data[result.rows.item(i).Key] = result.rows.item(i).Value;
              }
            }
          }
          // if (result.rows.length && !$filter('checkEmptyProps')(propertyCache.day_start)) {
          if (result.rows.length && (propertyCache.day_start.style != "" && propertyCache.day_start.sessionPlan != "" && propertyCache.day_start.siluhoutteid != "" && propertyCache.day_start.key2 != "" && propertyCache.day_start.key1 != "" )) {
            cache.startDayAvailable = true;
          } else{
            cache.startDayAvailable = false;
            ModalViews.getView("linesettings").show();
            $log.debug("day start not available go to day start view [empty]");
          }
        }, function (result) {
          //go to day start page
          ModalViews.getView("linesettings").show();
          $log.debug("day start go to day start view [error]");
          return false;
        });
      },


      isAvailableConfigurations: function () {
        //check configuration
        var _self = this;

        if (cache.configAvailable) {
          $log.debug("Server Configuration is available");
          return true;
        }

        $log.debug("Checking if configurations are available");

        dataPersistenceService.selectConfigurations().then(function (result) {
          $log.debug("Configuration result");
          $log.debug(result);

          for (var i = 0; i < result.rows.length; i++) {
            if(propertyCache.config.hasOwnProperty(result.rows.item(i).Key)){
              $log.debug(result.rows.item(i).Key ,result.rows.item(i).Value);
              propertyCache.config[result.rows.item(i).Key] = result.rows.item(i).Value;
            }
            if(propertyCache.factoryConfigs.hasOwnProperty(result.rows.item(i).Key)){
              $log.debug(result.rows.item(i).Key ,result.rows.item(i).Value);
              propertyCache.factoryConfigs[result.rows.item(i).Key] = result.rows.item(i).Value;
            }
          }
          // if (result.rows.length && $filter('checkEmptyProps')(propertyCache.config)) {
          //   cache.configAvailable = true;
          // }

          if (result.rows.length && (propertyCache.config.dataIp != "" && propertyCache.config.syncIp != "" && propertyCache.config.factory != "" && propertyCache.config.tenant != "")) {
            cache.configAvailable = true;
          }
          else{
            ModalViews.getView("config").show();
          }
        }, function (result) {
          //go to config page
          ModalViews.getView("config").show();
          return false;
        });
      }
    };
  }]);
