var angular = require('angular');
require('../modules');
require('../services/CommonNotionService');
require('../../linker/services/LinkerService');

var module = angular.module('flow.directives');

module.directive('sinoCommonnotionSelect', function() {
  return {
    restrict: 'E',
    templateUrl: 'views/flow/commonNotionSelect.tpl.html',
    replace: true,
    scope: {
      onSelect: '&'
    },
    controller: 'sinoCommonnotionSelectCtrl',
    controllerAs: 'sinoCommonnotionSelectCtrl'
  };
})
.controller('sinoCommonnotionSelectCtrl', function(CommonNotionService, LinkerService) {
  var userId = LinkerService.currentUserId;
  var ctrl = this;
  function getCommonNotions() {
    CommonNotionService.getCommonNotions(userId).then(function(commonNotions) {
      ctrl.commonNotions = commonNotions ? commonNotions : [];
    });
  }
  getCommonNotions();
  ctrl.deleteCommonNotion = function(commonNotionId, index, $event) {
    $event.stopPropagation();
    $event.preventDefault();
    CommonNotionService.deleteCommonNotion(commonNotionId).then(function() {
      ctrl.commonNotions.splice(index, 1);
    });
  };
})
.directive('sinoNotionItemRadio', function() {
  return {
    restrict:'C',
    link: function(scope, element) {
      var parentDom = element.parent()[0];
      element.on('tap', function() {
        angular.element(parentDom.querySelectorAll('.selected'))
          .removeClass('selected');
        element.addClass('selected');
      });
    }
  };
});
