'use strict';

var	angular	= require('angular');
require('../modules');
require('../services/GestureScreenContext');
require('../../login/services/LoginService');
require('../services/GestureScreenPasswordService');
require('../../../commons/services/AppConfig');

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

module.controller('modifyGestureScreenController', function(GestureScreenContext, $scope,
 LinkerService, CommonService, LoginService, GestureScreenPasswordService, $state,
 $toast, $ionicPopup, Timer, AppConfig) {
	var height = window.screen.height,
		width = window.screen.width,
		gesturepassword = null;

	$scope.count = 5;

	var screenContext = new GestureScreenContext(width, height, function(passwords) {
		var validate = passwords.join('') === gesturepassword;
		if (validate) {
			$state.go('gesturepassword.setGesturePwd');
		} else if (!validate && passwords.length > 0) {
			$scope.isStateNo = true;
			$scope.count--;
			if ($scope.count <= 0) {
				$scope.count++;
				$ionicPopup.confirm({
					title: '提示',
					content: '您已经连续5次输错手势，手势解锁已关闭，请重新登录。',
					okText: '确定',
					cancelType: 'button-cancel-display'
				}).then(function(res) {
					if (res) {
						LoginService.logout().then(function() {
							if(!AppConfig.getCustomResult('passwordLoginEnable')) {
								$state.go('calogin');
							} else {
								$state.go('login'); // 定制是否有密码登录页面
							}
						});
					}
				});
			}

		}
		return validate;
	});

	function getLoginUser() {
      $scope.userId = LinkerService.currentUserId;
	}

	function getGesturePassword() {
		var userId = LinkerService.currentUser.userId;
		gesturepassword = GestureScreenPasswordService.getPassword(userId);
	}

	$scope.forgetPassword = function() {
		var user = LinkerService.currentUser;
		GestureScreenPasswordService.setPassword(user.userId, '');
		LoginService.logout().then(function() {
			$state.go('login');
		});
	};

	$scope.otherLogin = function() {
		LoginService.logout().then(function() {
			$state.go('gesturepassword.otherlogin');
		});
	};

	$scope.goBack = function() {
		$state.go('core-setting');
	};

	getLoginUser();
	getGesturePassword();

	var layout = screenContext.layout;
	$scope.topcontentStartY = layout.top.content.startY;
	$scope.bottomContentStartY = layout.bottom.content.startY - 15;
	$scope.screenContext = screenContext;
	$scope.delayLoadGesturePassword = false;
	Timer.delay(function() {
		$scope.delayLoadGesturePassword = true;
	}, 200);
});

