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

var module = angular.module('commons.directives.sinoGoBackButton');
var historyStates = [];
var inBacking = false;

module.run(function($rootScope) {
  $rootScope.$on('$stateChangeSuccess', function(
    event, toState, toParams, fromState, fromParams) {
    if ((!inBacking) && fromState) {
      if (toState.name === fromState.name) {
        var prev = getPrevState();
        if (prev) {
          prev.params = fromParams;
        }
      } else {
        historyStates.push({
          state: fromState,
          params: fromParams,
          coreState: /^core\-/.test(fromState.name)
        });
      }
    }
    inBacking = false;
  });
});

/** 启动项 */
module.run(function($toast, $ionicPlatform, $state, Timer) {
  function setBackButtonEvent() {
    var exitApp = false;
    function backButtonEvent(e) {
      e.preventDefault();
      if (exitApp) {
        ionic.Platform.exitApp();
        return false;
      }

      var level = $state.current.data ? $state.current.data.level : 0;
      if (level === 0) {
        $toast.showLongCenter('再按一次退出移动办公');
        exitApp = true;
        Timer.delay(function() {
          exitApp = false;
        }, 5000);
      }
    }

    $ionicPlatform.registerBackButtonAction(backButtonEvent, 102);
  }

  setBackButtonEvent();
});

function getPrevState() {
  return historyStates.length > 0? historyStates[historyStates.length - 1] : null;
}

function popPrevState() {
  var prev = historyStates.pop();
  if (prev && prev.coreState) {
    historyStates = [];
  }
  return prev;
}

module.directive('sinoGoBackButton', function(
  $rootScope, $state, $ionicPlatform, $ionicViewSwitcher, $sinoGoBackDelegate) {
  function getTitleFromState(state) {
    if (state && state.state && state.state.data) {
      return state.state.data.title;
    }
  }

  return {
    restrict: 'A',
    link: function(scope, element, attr) {
      var defaultBackAction = attr.defaultBackAction,
        prevState = getPrevState(),
        prevCoreState = prevState && prevState.coreState;

      if (prevState) {
        var html = element[0].innerHTML;
        var title = getTitleFromState(prevState) || html || '返回';
        element[0].innerHTML = title;
      }

      var actions = ['send', 'approve', 'notApprove', 'finish', 'transfer'];
      scope.$parent.$on('sino.flow.action', function(event, action) {
        if (_.indexOf(actions, action) >= 0) {
          if (attr.goBackLevel && attr.goBackLevel > 1) {
            for (var i = 1; i < attr.goBackLevel; i++) {
              popPrevState();
              prevState = getPrevState();
              prevCoreState = prevState && prevState.coreState;
            }
          }

          goBack();
        }
      });

      function goBack() {
        inBacking = true;
        popPrevState();
        $ionicViewSwitcher.nextDirection(attr.sinoNavDirection);
        if (prevCoreState) {
          $state.go(prevState.state, prevState.params);
        } else if(defaultBackAction) {
          scope.$eval(defaultBackAction);
        } else if (prevState) {
          $state.go(prevState.state, prevState.params);
        }
        _deregisterBackButton();
      }
      element.on('click', goBack);
      $sinoGoBackDelegate.set(goBack);

      var _deregisterBackButton = $ionicPlatform.registerBackButtonAction(
        goBack, attr.priority ? parseInt(attr.priority) : 104);

      scope.$on('$destroy', function() {
        _deregisterBackButton();
      });
    }
  };
})
.factory('$sinoGoBackDelegate', function() {
  var _backAction;
  return {
    back: function() {
      _backAction && _backAction();
      _backAction = null;
    },

    set: function(backAction) {
      _backAction = backAction;
    }
  };
});
