/** 处理modal弹框返回键*/


var angular = require('angular');
require('../modules');

angular
  .module('commons.directives.sinoModalBackButton')
  .directive('sinoModalBackButton', sinoModalBackButton);

/** @ngInject*/
function sinoModalBackButton($ionicPlatform) {
  return {
    restrict: 'A',
    link: link
  }

  function link(scope, element, attrs) {
    var deregisterBackButton = function() {};
    
    init();

    function init() {
      scope.$on('$destroy', function() {
        unRegister();
      });
      scope.$on('modal.shown', function() {
        registerDeviceBackButton(attrs, backButtonFn);
        registerBackButton(scope, element, backButtonFn);
      })
      scope.$on('modal.hidden', function() {
        unRegister();
      });
      scope.$on('modal.removed', function() {
        unRegister();
      });
    }
    
    function backButtonFn() {
      scope.$eval(attrs.sinoModalBackButton);
    }
    
    function registerDeviceBackButton(attrs, backButtonFn) {
      deregisterBackButton = $ionicPlatform.registerBackButtonAction(backButtonFn, 
        (attrs.priority) ? Number.parseInt(attrs.priority) : 201);
    }
    
    function unRegister() {
      deregisterBackButton && deregisterBackButton();
      unRegisterEvent();
    }
    
    function unRegisterEvent() {
      element.unbind('click', onClick);
    }
    
    function onClick(event) {
      scope.$apply(function() {
        backButtonFn();
      });
    }
    
    function registerBackButton(scope, element, backButtonFn) {
      element.on('click', onClick);
    }
  }
}
