'use strict';
//dependent upon on Bootstrap

app.directive('testMacro', function () {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      systemId: '=',
      devices: '=',
      macro: '='
    },
    template: '<button class="btn btn-primary btn-fw" ng-click="test(systemId, devices, macro)">Test</button>',
    controller: function($scope, $http, $q, $timeout, $modal, toastr) {
      var promise,
          currentStep = 0,
          FUNC_TYPE = 1,
          DELAY_TYPE = 2,
          canceller = $q.defer(),
          modal = $modal({scope: $scope, title: 'Test macro', backdrop: 'static', placement: 'top', template: 'views/modal-tpls/test-macro.html',  show: false});


      $scope.cancel = function () {
        console.log(promise);
        console.log(canceller);

        if ($scope.macro[currentStep].type === FUNC_TYPE) {
          console.log('HTTP req cancelled');
          canceller.resolve('User cancelled');
        } else if ($scope.macro[currentStep].type === DELAY_TYPE) {
          console.log('Timer cancelled');
          $timeout.cancel(promise);
        } else {

        }
      };


      $scope.test = function(systemId, devices, macro) {
        console.log(systemId);
        console.log(devices);
        console.log(macro);


        //Resets
        currentStep = 0;
        canceller = $q.defer();
        $scope.macroCompleted = false;

        _.forEach(macro, function (step) {
          step.isTesting = false;
          step.isError = false;
          step.isCompleted = false;
        });


        function makeRequest (step) {
          switch (step.type) {
            case FUNC_TYPE:
              var jsonTestData,
                  testData = {},
                  urlData = '/api/cloud/test',
                  device = _.where(devices, { 'id': step.device_id })[0],
                  func = _.where(device.funcs, {'id': step.func })[0];

              if(device.target_type === 1) {
                testData = { "systemId" : systemId, "type" : device.target_type,
                  "addr" : device.target_addr, "port" : device.target_port, "repeat" : device.repeat_macro,
                  "data" : func.data, "ir_type": func.type };
              }
              else {
                testData = { "systemId" : systemId, "type" : device.target_type,
                  "addr" : device.target_addr, "port" : device.target_port, "repeat" : device.repeat_macro,
                  "ramp_start" : device.ramp_start, "ramp_speed" : device.ramp_speed, "auto_cr" : device.auto_cr,
                  "data" : func.data };
              }

              jsonTestData = JSON.stringify(testData);
              console.log(jsonTestData);

              return $http({ method: 'POST', url: urlData, data: jsonTestData, timeout: canceller.promise }).success(handleSuccess).error(handleError);

            case DELAY_TYPE:
              promise = $timeout(function () {
                console.log('Timeout callback');
                macro[currentStep].isTesting = false;
                macro[currentStep].isCompleted = true;

                console.log(currentStep);
                makeNextRequest();
              }, step.value);
              return promise;
            default:
              promise = $timeout(function () {
                console.log('Default callback');
                macro[currentStep].isTesting = false;

                console.log(currentStep);
                makeNextRequest();
              }, 0);
              return promise;
          }
        }


        function makeNextRequest() {
          if (currentStep+1 < macro.length) {
            currentStep++;
            macro[currentStep].isTesting = true;
            makeRequest(macro[currentStep]);
          } else {
            $scope.macroCompleted = true;
          }

        }



        function handleSuccess(data) {
          console.log(data);

          if (data.result) {
            toastr.success('Test command sent');

            macro[currentStep].isTesting = false;
            macro[currentStep].isCompleted = true;
          } else {
            macro[currentStep].isTesting = false;
            macro[currentStep].isError = true;
          }

          console.log(currentStep);
          makeNextRequest();
        }


        function handleError(data) {
          console.log(data);
          macro[currentStep].isTesting = false;
          macro[currentStep].isError = true;
          makeNextRequest();
        }

        macro[currentStep].isTesting = true;
        modal.$promise.then(modal.show);

        makeRequest(macro[currentStep]);

      };
    }
  };
});
