'use strict';
//dependent upon on Bootstrap

app.directive('testFunction', function() {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      systemId: '=',
      roomId: '=',
      device: '=',
      func: '='
    },
    template: '<button class="btn btn-primary" ng-click="test(systemId, roomId, device, func)">Test it!</button>',
    controller: function($scope, $http, toastr, Systems) {

      $scope.test = function(systemId, roomId, device, func) {
        console.log(systemId);
        console.log(roomId);
        console.log(device);

        var urlData = '/api/cloud/test';

        if (!device.hasOwnProperty('target_type') || !device.hasOwnProperty('target_addr') || !device.hasOwnProperty('target_port')) {
          device = Systems.getDevice(roomId, device.device_id);
          console.log(device);
        }

        

        var testData = {};
        if(device.target_type === 1) {
          testData = { "systemId" : systemId, "type" : device.target_type,
            "addr" : device.target_addr, "port" : device.target_port, "repeat" : device.repeat_macro,
            "ir_type": func.type, "data" : func.data };
        }
        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 };
        }

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

        $http({
          method: 'POST',
          url: urlData,
          data: jsonTestData
        }).
        success(function(data) {
          if(data.result === true) {
            toastr.success('Test command sent');
          }
          else {
            toastr.error(data.error);
          }
        }).
        error(function() {
          toastr.error("Please try again");
        });
      };
    }
  };
});
