'use strict';

// HostNames controller
angular.module('hostNames').controller('HostNamesController', ['$scope', '$stateParams', '$location', 'Authentication', 'HostNames',
    function ($scope, $stateParams, $location, Authentication, HostNames) {
      $scope.authentication = Authentication;
      $scope.SearchName = '';
      $scope.SearchHostID = '';

      $scope.sortType = 'name'; // set the default sort type
      $scope.sortReverse = false;  // set the default sort order

      // input array
      $scope.hostName = new HostNames({
        semaphore: 'Open',
        name: '',
        hostType: '',
        envType: '',
        originatingSource: '',
        originatingID: '',
        note: '',
        PBB: '',
        relatedApplications: [],
        address: ''
      });

      $scope.hostNames= [HostNames];
      $scope.generatedList=[];

      $scope.valHostName = new HostNames({
        semaphore: 'Open',
        name: '',
        hostType: '',
        envType: '',
        originatingSource: '',
        originatingID: '',
        note: '',
        PBB: '',
        relatedApplications: [],
        address: ''
      });

      $scope.hostNameRequest = {
        hostName: HostNames,
        instanceCt: '',
      };

      // Create new HostName
      $scope.create = function (isValid) {
        $scope.error = null;

        if (!isValid) {
          $scope.$broadcast('show-errors-check-validity', 'hostNameForm');
          return false;
        }

        // Create new hostName object
        var hostName = new HostNames({
          semaphore: this.hostName.semaphore,
          name: this.hostName.name,
          hostType: this.hostName.hostType,
          envType: this.hostName.envType,
          originatingSource: this.hostName.originatingSource,
          originatingID: this.hostName.originatingID,
          note: this.hostName.note,
          PBB: this.hostName.PBB,
          relatedApplications: this.hostName.relatedApplications,
          address: this.hostName.address
        });

        // Redirect after save
        hostName.$save(function (response) {
          $location.path('hostNames/' + response._id);
          // Clear form fields
          $scope.hostName=null;
        }, function (errorResponse) {
          $scope.error = errorResponse.data.message;
        });
      };

      // Remove existing HostName
      $scope.remove = function (hostName) {
        if (hostName) {
          hostName.$remove();

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

      // Duplicate existing hostName
      $scope.replicate = function (hostName) {
        if (hostName) {
          var hn = $scope.deepCopyHostName(hostName);
          hn.$save(function () {
            $location.path('hostNames/' + hostName._id + '/edit');
          }, function (errorResponse) {
            $scope.error = errorResponse.data.message;
          });
        }
      };

      // Update existing HostName
      $scope.update = function (isValid) {
        $scope.error = null;
        if (!isValid) {
          $scope.$broadcast('show-errors-check-validity', 'hostNameForm');
          return false;
        }

        $scope.hostName.$update(function () {
          $location.path('hostNames/' + $scope.hostName._id);
        }, function (errorResponse) {
          $scope.error = errorResponse.data.message;
        });
      };

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

      // Find a list of HostNames with specified hostType, envType and commonName
      $scope.findByHEC = function (myHostNameRequest) {
        //var listOfNames = HostNames.query({ 'hostType':myHostType, 'envType':myHostType }, function () {
        HostNames.query({ envType:myHostNameRequest.hostName.envType, hostType:myHostNameRequest.hostName.hostType, 'commonName':myHostNameRequest.hostName.address.commonName }, function (listOfNames) {
          // listOfNames needs a sort method.  Seems like not an array
          $scope.generatedList = listOfNames.sort(function(obj1, obj2){
            return obj1.name.localeCompare(obj2.name);
          });
        });
      };

      // Find existing HostName ID
      $scope.findOne = function () {
        // Callback set up  won't get instant response  Just a promise
        $scope.hostName = HostNames.get({
          hostNameId: $stateParams.hostNameId
        });
      };

    // Duplicate existing hostName
      $scope.deepCopyHostName = function (hostName) {
        if (hostName) {
          var myHostName = new HostNames({
            semaphore: hostName.semaphore,
            name: hostName.name,
            hostType: hostName.hostType,
            envType: hostName.envType,
            originatingSource: hostName.originatingSource,
            originatingID: hostName.originatingID,
            note: hostName.note,
            PBB: hostName.PBB,
            relatedApplications: hostName.relatedApplications,
            address: hostName.address
          });
          return (myHostName);
        }
        return('');
      };

      // Find host names and the last one
      $scope.hostNameSearch = function (isValid) {
        console.log('hostNameSearch');
        $scope.error = null;

        $scope.hostNameRequest.hostName.originatingSource = 'Remy Generated';
        var myDate = new Date();
        var myNum = myDate.getTime();
        var myTimeStr = myNum.toString();
        $scope.hostNameRequest.hostName.originatingID = myTimeStr;
        $scope.hostNameRequest.hostName.relatedApplications = [];

        if (!isValid) {
          $scope.$broadcast('show-errors-check-validity', 'hostNameForm');
          return false;
        }

        // Create new hostName object
        var myHostName = $scope.deepCopyHostName(this.hostNameRequest.hostName);
        console.log('myHostName.relatedApplications = %j',myHostName.relatedApplications);

        //http://theholmesoffice.com/mongoose-and-node-js-tutorial/
        console.log('myHostName: %j', myHostName);
        // call server side generate
        //$scope.hostName.$generate(function (myInstanceCt, response) {
        console.log('1 **** hostType: ' + myHostName.hostType + '  envType: ' + myHostName.envType + '  address: '+ myHostName.address.commonName);
        //$scope.findByHEC(myHostName.hostType, myHostName.envType, myHostName.address.commonName);
        $scope.findByHEC($scope.hostNameRequest);
      };

      function zeroFrontPad(numberString, length) {
        var zeroString = '';
        var retNumberString = '';
        for (var ct = 0; ct < length; ct++) {
          zeroString = zeroString+'0';
        }
        if (numberString.length < length) {
          retNumberString = (zeroString.toUpperCase()+numberString).slice(-length);
        }
        return retNumberString.toUpperCase();
      }

      function saveHandler(err) {
        if (err) {
          console.error('Save error: '+ err);
        }
      }

      // Generate new Host Names
      $scope.generate = function () {
        console.log('Generate Host Names');
        $scope.error = null;

        if ($scope.generatedList.length > 0) {
          var lastHostName = $scope.generatedList[$scope.generatedList.length-1].name;

          // Determine next set of host names
          var numberStart=lastHostName.search('[0-9]');
          //var hostNumberString = '0DA1';
          var hostNumberString = lastHostName.substring(numberStart);
          var newHostNames = [];
          var hostNumber = parseInt(hostNumberString,36)+1;

          //console.log('lastHostName: '+ lastHostName + ' Begin new array with hostNumber:'+hostNumber);
          for (var ct=0;ct < $scope.hostNameRequest.instanceCt; ct++) {
            var b36String = hostNumber.toString(36);
            var numberString = zeroFrontPad(b36String,4);

            // Create new hostName object
            var newHostName = new HostNames({
              semaphore: 'Open',
              name: lastHostName.substring(0,numberStart) + numberString,
              hostType: this.hostNameRequest.hostName.hostType,
              envType: this.hostNameRequest.hostName.envType,
              originatingSource: this.hostNameRequest.hostName.originatingSource,
              originatingID: this.hostNameRequest.hostName.originatingID,
              note: this.hostNameRequest.hostName.note,
              PBB: this.hostNameRequest.hostName.PBB,
              relatedApplications: this.hostNameRequest.hostName.relatedApplications,
              address: this.hostNameRequest.hostName.address
            });
            //console.log('numberString:' + numberString + '  newHostName= %j', newHostName);
            newHostNames.push(newHostName);
            //console.log(ct + ': newHostNames[ct] = %j', newHostNames);
            hostNumber = parseInt(numberString,36)+1;
            console.log('hostNumber: ' + hostNumber);
          }

          for (var i in newHostNames) {
            // Save hostName with semaphore lock

            var myHostName = newHostNames[i];
            //console.log('save myHostName %j', myHostName);
            myHostName.$save();
          }
        }
        // ReDirect to list view
        $location.path('hostNames/list');
      };

/*******************************************************************************
 * 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);
            }
          }
          else {
            console.error('Source object is undefined for addMember');
          }
        }
        else {
          console.error('Target object is undefined for addMember');
        }
        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--;
          }
        }
        else {
          console.error('Target object is undefined for removeMember');
        }
        return (myIndex);
      };

      $scope.saveMember = function (source, target, myIndex) {
        console.log('source: '+source+'  target: %j',target+'  myIndex ='+myIndex+ ' targetLength:'+ target.length);
        if (angular.isDefined(target)) {
          if (angular.isDefined(source)) {
            if (myIndex > -1 && myIndex <= target.length) {
              target[myIndex] = source;
            }
          }
          else {
            console.error('Source object is undefined for saveMember');
          }
        }
        else {
          console.error('Target object is undefined for saveMember');
        }
      };

/*******************************************************************************
 * 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.addRelatedApplication = function(target) {
        if (angular.isDefined(target)) {
          var myLen = target.push({
            MOTSID:'',
            MOTSAcronym:'',
            MOTSName:''
          });
          return myLen;
        }
        else {
          console.error('Target object is undefined for addRelatedApplication');
        }
      };
    }
]);

