/**
 * Created by shadeeka on 12/21/15.
 */
angular.module('app.services')
  .factory('cacheViews', [ '$log','$http', function ($log ,$http) {

    return {
      toOperations:-1,
      toIssues:-1,
      toRejects:-1,
      issuesToRender:[],
      rejectsToRender:[],
      issueListToSave:[],
      rejectListToSave:[],
      defect:{}
    };
  }])
// =========================================================================
// Issue filtering service
// =========================================================================
  .factory('issuesCache', ['$log', '$q', '$http', 'defectCategories', '$filter', 'propertyCache','dataPersistenceService', function ($log, $q, $http, defectCategories, $filter ,propertyCache,dataPersistenceService) {
    var issueMap = {}, rejectMap={}, issues = [], operations = [], model = {}, groups = [];
    var issuesCache = {
      issues: [],
      rejects:[],
      operations: [],
      model: {},
      groups: [],
      issueMap: {},
      rejectMap:{},
      opsMap: {},
      selectedOperations:[],
      defaultOps:[],
      //load issues from database
      init: function () {
        var _self = this;
        var deferred = $q.defer();
       defectCategories.getCategories().$promise.then(function (res) {
          deferred.resolve(true);
          _self.model = res;
          _self.issues = res.issues;
          _self.operations = res.operations;
          _self.rejects = res.rejects;
          _self.defaultOps = res.operations;
          _self.loadIssue();
          _self.loadRejects();
          _self.getCartonSizeList();
        });
        return deferred.promise;
      },

      checkForRecentStyleChange:function(){
        var _self =this;
        var string = localStorage.getItem("ops_"+propertyCache.day_start.style.trim());
        if(localStorage.getItem("ops_"+propertyCache.day_start.style.trim()))
        _self.selectedOperations =JSON.parse(string);
        else
          _self.selectedOperations=[];
      },

      loadOperations:function(applyScope){
        var _self = this;
        _self.operations=[];
        var deferred = $q.defer();
        if(localStorage.getItem("ops_"+propertyCache.day_start.style.trim())){
          deferred.resolve(applyScope);
        }
        else{
          //take it from database
          var style="";
          if(configData.defaultStyle=="") {
            style=propertyCache.day_start.style;
          }else{
            style=configData.defaultStyle;
          }
          dataPersistenceService.selectStyleOperations(style).then(function (response) {
            for(var i =0 ;i < response.rows.length;i++){
              _self.operations.push(JSON.parse(response.rows.item(i).Operation));
              $log.log("Operation loading ------------> ",JSON.parse(response.rows.item(i).Operation));
            }
            //angular.extend(_self.operations,_self.defaultOps);
            angular.forEach(_self.defaultOps,function(ops,index){
              _self.operations.push(ops);
            });
            localStorage.setItem("ops_"+propertyCache.day_start.style.trim(),JSON.stringify(_self.operations));
            _self.selectedOperations=[];
            deferred.resolve(applyScope);
          });
        }

        return deferred.promise;
      },
      loadIssue:function(applyScope){
        var _self = this;
        _self.issues=[];
        var deferred = $q.defer();
        if(localStorage.getItem("issueList")){
          _self.issues = JSON.parse(localStorage.getItem("issueList"));
          deferred.resolve(applyScope);
        }else {
          //take it from database
          dataPersistenceService.selectIssues().then(function (response) {
            //for (var i = 0; i < response.rows.length; i++) {
              _self.issues.push(JSON.parse(response.rows.item(0).IssueName));
              $log.log("Issue loading ------------> ", JSON.parse(response.rows.item(0).IssueName));
           // }
            localStorage.setItem("issueList",JSON.stringify(_self.issues));
            deferred.resolve(applyScope);
          });
        }
      },
      loadRejects:function(applyScope){
        var _self = this;
        _self.rejects=[];
        var deferred = $q.defer();
        if(localStorage.getItem("rejectList")){
          _self.rejects = JSON.parse(localStorage.getItem("rejectList"));
          deferred.resolve(applyScope);
        }else {
          //take it from database
          dataPersistenceService.selectRejects().then(function (response) {
            // for (var i = 0; i < response.rows.length; i++) {
              _self.rejects.push(JSON.parse(response.rows.item(0).RejectName));
              $log.log("rejects loading ------------> ", JSON.parse(response.rows.item(0).RejectName));
            // }
            localStorage.setItem("rejectList",JSON.stringify(_self.rejects));
            deferred.resolve(applyScope);
          });
        }
      },

      getCartonSizeList:function(applyScope){
        var _self = this;
        _self.sizeList=[];
        var deferred = $q.defer();
        if(localStorage.getItem("sizeList")){
          _self.sizeList = JSON.parse(localStorage.getItem("sizeList"));
          deferred.resolve(applyScope);
        }else {
          //take it from database
          dataPersistenceService.selectBuyerWiseSizeList().then(function (response) {
            for (var i = 0; i < response.rows.length; i++) {
              _self.sizeList.push(JSON.parse(response.rows.item(i).SizeName));
              console.log("getCartonSizeList ------------> ", JSON.parse(response.rows.item(i).SizeName));
            }
            localStorage.setItem("sizeList",JSON.stringify(_self.sizeList));
            // propertyCache.setSizeList(JSON.parse(localStorage.getItem("sizeList")));
            deferred.resolve(applyScope);
          });
        }
      },

      getAllIssues: function () {
        return this.issues;
      },

      getAllRejects: function () {
        return this.rejects;
      },

      getAllOperations: function () {
        return this.operations;
      },

      getAllGroups: function () {
        return this.groups;
      },

      getSelectedOperations:function(){

      var _self =this;

      var selectedOps =$filter('filter')(_self.selectedOperations, {ischecked:true});

      return angular.copy(selectedOps);
      },

      getFilteredIssues: function (categories) {
        var dst = [];
        var _self = this;

        angular.forEach(categories, function (cat, key) {
          if (cat) {
            angular.forEach(_self.issueMap[key], function (issue, index) {
              dst.push(issue);
            })
          }
        });
        return dst;//return filtered array
      },

      getFilteredRejects: function (categories) {
        var dst = [];
        var _self = this;

        angular.forEach(categories, function (cat, key) {
          if (cat) {
            angular.forEach(_self.rejectMap[key], function (reject, index) {
              dst.push(reject);
            })
          }
        });
        return dst;//return filtered array
      },

      getOperationsForCurrentStyle:function(){
        var ops=[];
        if(localStorage.getItem("ops_"+propertyCache.day_start.style.trim())){
          ops = JSON.parse(localStorage.getItem("ops_"+propertyCache.day_start.style.trim()));
        }
        return ops;
      },

      updateOperations:function(operations){
        var _self = this;
        _self.selectedOperations =angular.copy(operations);
        localStorage.setItem("ops_"+propertyCache.day_start.style.trim(),JSON.stringify(_self.selectedOperations));
      },

      getOperationByGroup: function (group) {
        var _self = this;
        var filter = {};
        filter[group] = true;

        var operationsByGroup = $filter('bygroup')(_self.operations, filter);
        return operationsByGroup;
      },

      getIssuesByGroup: function (group) {
        var _self = this;
        var filter = {};
        filter[group] = true;

        var operationsByGroup = $filter('bygroup')(_self.issues[0], filter);
        return operationsByGroup;
      },

      getRejectsByGroup: function (group) {
        var _self = this;
        var filter = {};
        filter[group] = true;

        var operationsByGroup = $filter('bygroup')(_self.rejects[0], filter);
        return operationsByGroup;
      },

      arrayObjectIndexOf:function(arr, obj){
      for(var i = 0; i < arr.length; i++){
        if(angular.equals(arr[i], obj)){
          return i;
        }
        };
       return -1;
       }
    };

    return issuesCache;
  }]);
