'use strict';

app.directive('deviceBtnEdit', function () {
  return {
    restrict: 'EA',
    replace: true,
    scope: {
      selectedBtn: '=',
      dbCon: '='
    },
    template: function(tElement, tAttrs) {
      var template;
      switch (tAttrs.content) {
        case 'add':
          template = '<button class="btn btn-menu" ng-click="showModal()">Add a button</button>';
          break;
        case 'edit':
        default:
          template = '<a title="Edit this button" ng-click="showModal()" ><i class="fa fa-fw fa-lg fa-pencil action-icon"></i></a>';
          break;
      }
      return template;
    },
    controller: function($scope, $element, $modal) {
      var editModal = $modal({ scope: $scope, title: 'Edit this button', template:'views/modal-tpls/device-edit-btn.html', show:false});
      
      function showModal() {
        $scope.newBtn = angular.copy($scope.selectedBtn);
        editModal.$promise.then(editModal.show);
      }
      function hideModal() {
        editModal.$promise.then(editModal.hide);
      }

      $scope.showModal = showModal;

      $scope.edit = function(oldValue, newValue) {
        console.log(oldValue);
        console.log(newValue);

        if (!newValue.hasOwnProperty('press_hold')) {
          newValue.press_hold = newValue.func.press_hold ? true:false;
        }

        if (!newValue.hasOwnProperty('image_name')) {
          newValue.image_name = '';
        }

        if (!newValue.hasOwnProperty('device_id')) {
          newValue.device_id = newValue.func.device_id;
        }

        if (!newValue.hasOwnProperty('room_id')) {
          newValue.room_id = newValue.func.room_id;
        }

        if (!newValue.hasOwnProperty('hidden_option')) {
          newValue.hidden_option = 0;
          newValue.activity = '';
          newValue.popup = 0;
        }
        
        _.assign(oldValue, newValue);

        hideModal();
      };
      
    }
  };
});