'use strict';

var angular = require('angular');
require('../modules');
require('../../appconfig/services/appFlowConfigService');
require('uiRouter');

var module = angular.module('gesturepassword.services');

module.factory('GesturePasswordService', function(LinkerService, $state, appFlowConfigService, CacheService) {

  var GesturePasswordService = {
    nextAction: function() {},
    completed: false,
    doComplete: doComplete,
    judgeGesturePassword: judgeGesturePassword,
    transferGesturePassword: transferGesturePassword,
    clear: clear
  };

  return GesturePasswordService;

  function doComplete() {
    CacheService.put('app_config_set_need_gesture_password', true);
    GesturePasswordService.completed = true;
    if (GesturePasswordService.nextAction) {
      GesturePasswordService.nextAction();
    }
  }

  function judgeGesturePassword(nextAction) {
    if (GesturePasswordService.completed) {
      return;
    }

    GesturePasswordService.nextAction = nextAction ? nextAction : GesturePasswordService.nextAction;
    GesturePasswordService.transferGesturePassword().then(function(gesturePassword) {
      if (appFlowConfigService.needGesturePassword() && gesturePassword) {
        $state.go('gesturepassword.validateGesturePwd');
      } else if (appFlowConfigService.needGesturePassword() &&
          !CacheService.get('app_config_set_need_gesture_password')) {
        $state.go('gesturepassword.setGesturePwd2Ignore');
      } else if (appFlowConfigService.needGesturePassword() && !gesturePassword) {
         $state.go('gesturepassword.setGesturePwd2');
      } else {
        doComplete();
      }
    });
  }

  /**
   * 版本v0.9.20
   * 由于存储手势密码的缓存中的key值已作修改，优化版本更新时候会引起的问题
   */
  function transferGesturePassword() {

    return LinkerService.getCurrentUser().then(function (loginUser) {
      var value, key;
      if (loginUser && loginUser.userNamePinyin) {
        key = loginUser.userId + '_' + loginUser.userNamePinyin[0];
      }

      value = localStorage.getItem(key);
      if (value) {
        localStorage.removeItem(key);
        localStorage.setItem('gesturepassword_' + loginUser.userId, value);
      }

      return localStorage.getItem('gesturepassword_' + loginUser.userId);
    });
  }

  function clear() {
    return LinkerService.getCurrentUser().then(function(loginUser) {
      return localStorage.removeItem('gesturepassword_' + loginUser.userId);
    });
  }
});
