'use strict';

// InfrastructureRequests controller
angular.module('infrastructureRequests').controller('InfrastructureRequestsController', ['$scope', '$stateParams', '$location', 'Authentication', 'InfrastructureRequests',
    function ($scope, $stateParams, $location, Authentication, InfrastructureRequests) {
      $scope.authentication = Authentication;
      
      // List sort setup
      $scope.Pattern1 = '';
      $scope.Pattern2 = '';      
      $scope.sortType = ['requestSource', 'requestID']; // set the default sort type
      $scope.sortReverse = false;  // set the default sort order

      $scope.infrastructureRequest = new InfrastructureRequests({
        requestSource: '',
        requestID: '',
        note: '',
        hostings:[],
        otherRequests:[]
      });

      $scope.hostingsIndex=-1;
      $scope.newHostingsIndex=-1;
      $scope.modifyHostingsIndex=-1;
      $scope.decomHostingsIndex=-1;
      $scope.environmentsIndex=-1;
      $scope.tenantQuotasIndex=-1;
      $scope.tenantQuotaComputeIndex=-1;
      $scope.tenantQuotaStorageIndex=-1;
      $scope.computesIndex=-1;
      $scope.storagesIndex=-1;
      $scope.workloadsIndex=-1;
      $scope.payloadsIndex=-1;
      $scope.mgtModelsIndex=-1;
      $scope.networkGatewaysIndex=-1;
      $scope.securitysIndex=-1;
      $scope.sitesIndex=-1;
      $scope.dependenciesIndex=-1;
      $scope.workloadComputeIndex=-1;
      $scope.workloadStorageIndex=-1;
      $scope.relatedApplicationsIndex=-1;
      $scope.packagesIndex=-1;

      $scope.otherRequestsIndex=-1;

      // Create new InfrastructureRequest
      $scope.create = function (isValid) {
        $scope.error = null;
        
        if (!isValid) {
          $scope.$broadcast('show-errors-check-validity', 'infrastructureRequestForm');
          return false;
        }

        // Create new address object
        var infrastructureRequest = new InfrastructureRequests($scope.infrastructureRequest);

        // Redirect after save
        infrastructureRequest.$save(function (response) {
          $location.path('infrastructureRequests/' + response._id);
          // Clear form fields
          $scope.requestSource = '';
          $scope.requestID = '';
          $scope.note = '';
          $scope.hostings = [];
          $scope.otherRequests = [];
        }, function (errorResponse) {
          $scope.error = errorResponse.data.message;
        });
      };

      // Remove existing InfrastructureRequest
      $scope.remove = function (infrastructureRequest) {
        if (infrastructureRequest) {
          infrastructureRequest.$remove();

          for (var i in $scope.infrastructureRequests) {
            if ($scope.infrastructureRequests[i] === infrastructureRequest) {
              $scope.infrastructureRequests.splice(i, 1);
            }
          }
        } else {
          $scope.infrastructureRequest.$remove(function () {
            $location.path('infrastructureRequests/list');
          });
        }
      };

      // Duplicate existing InfrastructureRequest
      $scope.replicate = function (infrastructureRequest) {
        if (infrastructureRequest) {
          var myObj = new InfrastructureRequests({
            requestSource: infrastructureRequest.RequestSource,
            requestID: infrastructureRequest.RequestID,
            note: infrastructureRequest.Note,
            hostings: infrastructureRequest.Hostings,
            otherRequests: infrastructureRequest.OtherRequests
          });
          myObj.$save(function () {
            $location.path('infrastructureRequests/' + infrastructureRequest._id + '/edit');
          }, function (errorResponse) {
            $scope.error = errorResponse.data.message;
          });
        }
      };

      // Update existing InfrastructureRequest
      $scope.update = function (isValid) {
        $scope.error = null;

        if (!isValid) {
          $scope.$broadcast('show-errors-check-validity', 'infrastructureRequestForm');
          return false;
        }        
        
        $scope.infrastructureRequest.$update(function () {
          $location.path('infrastructureRequests/' + $scope.infrastructureRequest._id);
        }, function (errorResponse) {
          console.log('error- ' + errorResponse.data.message);
          $scope.error = errorResponse.data.message;
        });
      };

      // Find a list of InfrastructureRequests
      $scope.find = function () {
        $scope.infrastructureRequests = InfrastructureRequests.query();
      };

      // Find existing InfrastructureRequest
      $scope.findOne = function () {
        // Callback set up  won't get instant response  Just a promise
        $scope.infrastructureRequest = InfrastructureRequests.get({
          infrastructureRequestId: $stateParams.infrastructureRequestId
        });
        
      };

/*******************************************************************************
 * General Purpose member functions
 *
 *******************************************************************************/
      $scope.addMember = function (source, target) {
        if (angular.isDefined(target)) {
          if (angular.isDefined(source)) {
            if (target.indexOf(source) < 0) {
              target.push(source);
            }
          }
        }
        return target.length;
      };

      // Remove array member on button click
      $scope.removeMember = function (target, myIndex) {
        if (angular.isDefined(target)) {
          if (myIndex > -1) {
            target.splice(myIndex,1);
            myIndex--;
          }
        }
        return (myIndex);
      };

      $scope.saveMember = function (source, target, myIndex) {
        console.log('source='+source+' target=%j'+' index'+myIndex);
        if (angular.isDefined(target)) {
          if (angular.isDefined(source)) {
            if (myIndex > -1 && myIndex <= target.length) {
              target[myIndex] = source;
              console.log('target updated');
            }
          }
        }
      };

/*******************************************************************************
 * Add sections
 *   Define all model components for use by HTML views
 *   Make sure there is an intital index variable for any array (value = -1)
 *
 *      User will click a button to initialize a section.  The values will be initialized to null.
 *      This will display the section in the HTML for input.
 *      Should check for non-null value in at least one section variable to avoid storing useless null values
 *
 *******************************************************************************/
      $scope.addHosting = function(hostTarget) {
        var myLen = hostTarget.push({
          type:'',
          note:'',
          newHostings:[],
          modifyHostings:[],
          decommHostings:[]
        });
        return myLen;
      };
      
      $scope.addNewHosting = function(newHostTarget) {
        var myLen = newHostTarget.push({
          packages:[],
          relatedApplications:[],
          environments:[]
        });
        return myLen;
      };

      $scope.addModifyHosting = function(modifyHostTarget) {
        var myLen = modifyHostTarget.push({
          target:'',
          computes:[],
          storages:[]
        });
        return myLen;
      };

      $scope.addDecommHosting = function(decommHostTarget) {
        var myLen = decommHostTarget.push({
          target:'',
          note:''
        });
        return myLen;
      };
      
      $scope.addEnvironment = function(environmentTarget) {
        var myLen = environmentTarget.push({
          supportClass:'',
          name:'',
          description:'',
          tenantQuotas:[],
          workloads:[]
        });
        return myLen;
      };

      $scope.addTenantQuota = function(tenantQuotaTarget) {
        var myLen = tenantQuotaTarget.push({
          name:'',
          description:'',
          flavor:'',
          type:'',
          sites:[],
          computes:[],
          storages:[]
        });
        return myLen;
      };

      $scope.addCompute = function(computeTarget) {
        var myLen = computeTarget.push({
          vCPU:'',
          CPU:'',
          RAM:'',
          certOS:'',
          certOSVer:''
        });
        return myLen;
      };

      $scope.addStorage = function(storageTarget) {
        var myLen = storageTarget.push({
          type:'',
          mgAmount:'',
          fileSystemPath:''
        });
        return myLen;
      };

      $scope.addWorkload = function(workloadTarget) {
        var myLen = workloadTarget.push({
          instanceCount:1,
          description:'',
          BMLRequired:'',
          payloads:[],
          IOPSMaxRequired:10,
          mgtModels:[],
          networkGateways:[],
          hypervisor:'',
          securitys:[],
          sites:[],
          computes:[],
          storages:[]
        });
        return myLen;
      };

      $scope.addPayload = function(payloadTarget) {
        var myLen = payloadTarget.push({
          containerSW:'',
          containerSWVer:'',
          NLSCharSet:'',
          NLSNCharCharSet:'',
          note:''
        });
        return myLen;
      };

      $scope.addMgtModel = function(mgtModelTarget) {
        var myLen = mgtModelTarget.push({
          type:'',
          note:''
        });
        return myLen;
      };

      $scope.addNetworkGateway = function(networkGatewayTarget) {
        var myLen = networkGatewayTarget.push({
          name:'',
          description:'',
          type:'',
          note:''
        });
        return myLen;
      };

      $scope.addSecurity = function(workloadSecurityTarget) {
        var myLen = workloadSecurityTarget.push({
          handles:'',
          stores:'',
          other:''
        });
        return myLen;
      };

      $scope.addSite = function(siteTarget) {
        var myLen = siteTarget.push({
          siteType:'',
          siteDescription:'',
          zone:'',
          cluster:'',
          address:{
            commonName:'',
            street1:'',
            street2:'',
            city:'',
            state:'',
            postalCode:'',
            country:'',
            floor:'',
            section:'',
            clli:''
          },
          dependencies:[]
        });
        return myLen;
      };

      $scope.addDependency = function(dependencyTarget) {
        var myLen = dependencyTarget.push({
          reason:'',
          type:'',
          note:''
        });
        return myLen;
      };

      $scope.addPackage = function(packageTarget) {
        var myLen = packageTarget.push({
          offeringName:'',
          offeringType:''
        });
        return myLen;
      };

      $scope.addRelatedApplication = function(relatedApplicationTarget) {
        var myLen = relatedApplicationTarget.push({
          MOTSID:'',
          MOTSAcronym:'',
          MOTSName:''
        });
        return myLen;
      };
      
      $scope.addOtherRequest = function(otherRequestTarget) {
        var myLen = otherRequestTarget.push({
          features:[],
          equipments:[],
          processes:[]
        });
        return myLen;
      };

      $scope.addFeature = function(featureTarget) {
        var myLen = featureTarget.push({
          name:'',
          action:'',
          description:'',
          note:''
        });
        return myLen;
      };
      
      $scope.addEquipment = function(equipmentTarget) {
        var myLen = equipmentTarget.push({
          name:'',
          ALMID:'',
          instanceCount:0,
          note:''
        });
        return myLen;
      };
      
      $scope.addProcess = function(processTarget) {
        var myLen = processTarget.push({
          handler:'',
          name:'',
          ALMTask:'',
          argumentLists:[],
          note:''
        });
        return myLen;
      };
      
      $scope.addArgumentList = function(argumentListTarget) {
        var myLen = argumentListTarget.push({
          UID:'',
          hostName:''
        });
        return myLen;
      };
      
 /*******************************************************************************
 *  Object member save/remove functions
 *   Functions to manipulate infrastructure object section variables
 *
 *   Only include functions for specific sections here.  General purpose is higher up in the file
 *
 *******************************************************************************/
      // Remove sections
      $scope.removeNewHosting = function (target, myIndex) {
        $scope.newHostingsIndex = $scope.removeMember(target, myIndex);
      };

      $scope.removePackage = function (target, myIndex) {
        $scope.packagesIndex = $scope.removeMember (target, myIndex);
      };

      $scope.removeRelatedApplication = function (target, myIndex) {
        $scope.relatedApplicationsIndex = $scope.removeMember(target, myIndex);
      };
    }
]);
