<commit_before>//
//  LoginViewController.swift
//  V2ex-Swift
//
//  Created by huangfeng on 1/22/16.
//  Copyright © 2016 Fin. All rights reserved.
//

import UIKit
import OnePasswordExtension
import Kingfisher
import SVProgressHUD
import Alamofire

public typealias LoginSuccessHandel = (String) -> Void

class LoginViewController: UIViewController {

    var successHandel:LoginSuccessHandel?

    let backgroundImageView = UIImageView()
    let frostedView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
    let userNameTextField = UITextField()
    let passwordTextField = UITextField()
    let codeTextField = UITextField()
    let codeImageView = UIImageView()
    let loginButton = UIButton()
    let cancelButton = UIButton()
    override func viewDidLoad() {
        super.viewDidLoad()

        self.hideKeyboardWhenTappedAround()
        
        //初始化界面
        self.setupView()

        //初始化1Password
        if OnePasswordExtension.shared().isAppExtensionAvailable() {
            let onepasswordButton = UIImageView(image: UIImage(named: "onepassword-button")?.withRenderingMode(.alwaysTemplate))
            onepasswordButton.isUserInteractionEnabled = true
            onepasswordButton.frame = CGRect(x: 0, y: 0, width: 34, height: 22)
            onepasswordButton.contentMode = .scaleAspectFit
            onepasswordButton.tintColor = UIColor.white
            self.passwordTextField.rightView = onepasswordButton
            self.passwordTextField.rightViewMode = .always
            onepasswordButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(LoginViewController.findLoginFrom1Password)))
        }

        //绑定事件
        self.loginButton.addTarget(self, action: #selector(LoginViewController.loginClick(_:)), for: .touchUpInside)
        self.cancelButton.addTarget(self, action: #selector(LoginViewController.cancelClick), for: .touchUpInside)
    }
    override func viewDidAppear(_ animated: Bool) {
        UIView.animate(withDuration: 2, animations: { () -> Void in
            self.backgroundImageView.alpha=1;
        }) 
        UIView.animate(withDuration: 20, animations: { () -> Void in
            self.backgroundImageView.frame = CGRect(x: -1*( 1000 - SCREEN_WIDTH )/2, y: 0, width: SCREEN_HEIGHT+500, height: SCREEN_HEIGHT+500);
        }) 
    }


    @objc func findLoginFrom1Password(){
        OnePasswordExtension.shared().findLogin(forURLString: "v2ex.com", for: self, sender: nil) { (loginDictionary, errpr) -> Void in
            if let count = loginDictionary?.count , count > 0 {
                self.userNameTextField.text = loginDictionary![AppExtensionUsernameKey] as? String
                self.passwordTextField.text = loginDictionary![AppExtensionPasswordKey] as? String

                //密码赋值后，点确认按钮
                self.loginClick(self.loginButton)
            }
        }
    }
    @objc func cancelClick (){
        self.dismiss(animated: true, completion: nil)
    }
    @objc func loginClick(_ sneder:UIButton){
        var userName:String
        var password:String
        if let len = self.userNameTextField.text?.Lenght , len > 0{
            userName = self.userNameTextField.text! ;
        }
        else{
            self.userNameTextField.becomeFirstResponder()
            return;
        }

        if let len =  self.passwordTextField.text?.Lenght , len > 0  {
            password = self.passwordTextField.text!
        }
        else{
            self.passwordTextField.becomeFirstResponder()
            return;
        }
        var code:String
        if let codeText = self.codeTextField.text, codeText.Lenght > 0 {
            code = codeText
        }
        else{
            self.codeTextField.becomeFirstResponder()
            return
        }
        
        V2BeginLoadingWithStatus("正在登录")
        if let onceStr = onceStr , let usernameStr = usernameStr, let passwordStr = passwordStr, let codeStr = codeStr {
            UserModel.Login(userName,
                            password: password,
                            once: onceStr,
                            usernameFieldName: usernameStr,
                            passwordFieldName: passwordStr ,
                            codeFieldName:codeStr,
                            code:code){
                (response:V2ValueResponse<String> , is2FALoggedIn:Bool) -> Void in
                if response.success {
                    V2Success("登录成功")
                    let username = response.value!
                    //保存下用户名
                    V2EXSettings.sharedInstance[kUserName] = username
                    
                    //将用户名密码保存进keychain （安全保存)
                    V2UsersKeychain.sharedInstance.addUser(username, password: password)
                    
                    //调用登录成功回调
                    if let handel = self.successHandel {
                        handel(username)
                    }
                    
                    //获取用户信息
                    UserModel.getUserInfoByUsername(username,completionHandler: nil)
                    self.dismiss(animated: true){
                        if is2FALoggedIn {
                            let twoFaViewController = TwoFAViewController()
                            V2Client.sharedInstance.centerViewController!.navigationController?.present(twoFaViewController, animated: true, completion: nil);
                        }
                    }
                }
                else{
                    V2Error(response.message)
                }
            }
            return;
        }
        else{
            V2Error("不知道啥错误")
        }
        
    }
    
    var onceStr:String?
    var usernameStr:String?
    var passwordStr:String?
    var codeStr:String?
    @objc func refreshCode(){
        
        Alamofire.request(V2EXURL+"signin", headers: MOBILE_CLIENT_HEADERS).responseJiHtml{
            (response) -> Void in
            
            if let jiHtml = response .result.value{
                //获取帖子内容
                //取出 once 登录时要用
                
                //self.onceStr = jiHtml.xPath("//*[@name='once'][1]")?.first?["value"]
                self.usernameStr = jiHtml.xPath("//*[@id='Wrapper']/div/div[1]/div[2]/form/table/tr[1]/td[2]/input[@class='sl']")?.first?["name"]
                self.passwordStr = jiHtml.xPath("//*[@id='Wrapper']/div/div[1]/div[2]/form/table/tr[2]/td[2]/input[@class='sl']")?.first?["name"]
                self.codeStr = jiHtml.xPath("//*[@id='Wrapper']/div/div[1]/div[2]/form/table/tr[4]/td[2]/input[@class='sl']")?.first?["name"]
                <commit_msg>登录失败时，将刷新验证码<commit_after>//
//  LoginViewController.swift
//  V2ex-Swift
//
//  Created by huangfeng on 1/22/16.
//  Copyright © 2016 Fin. All rights reserved.
//

import UIKit
import OnePasswordExtension
import Kingfisher
import SVProgressHUD
import Alamofire

public typealias LoginSuccessHandel = (String) -> Void

class LoginViewController: UIViewController {

    var successHandel:LoginSuccessHandel?

    let backgroundImageView = UIImageView()
    let frostedView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
    let userNameTextField = UITextField()
    let passwordTextField = UITextField()
    let codeTextField = UITextField()
    let codeImageView = UIImageView()
    let loginButton = UIButton()
    let cancelButton = UIButton()
    override func viewDidLoad() {
        super.viewDidLoad()

        self.hideKeyboardWhenTappedAround()
        
        //初始化界面
        self.setupView()

        //初始化1Password
        if OnePasswordExtension.shared().isAppExtensionAvailable() {
            let onepasswordButton = UIImageView(image: UIImage(named: "onepassword-button")?.withRenderingMode(.alwaysTemplate))
            onepasswordButton.isUserInteractionEnabled = true
            onepasswordButton.frame = CGRect(x: 0, y: 0, width: 34, height: 22)
            onepasswordButton.contentMode = .scaleAspectFit
            onepasswordButton.tintColor = UIColor.white
            self.passwordTextField.rightView = onepasswordButton
            self.passwordTextField.rightViewMode = .always
            onepasswordButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(LoginViewController.findLoginFrom1Password)))
        }

        //绑定事件
        self.loginButton.addTarget(self, action: #selector(LoginViewController.loginClick(_:)), for: .touchUpInside)
        self.cancelButton.addTarget(self, action: #selector(LoginViewController.cancelClick), for: .touchUpInside)
    }
    override func viewDidAppear(_ animated: Bool) {
        UIView.animate(withDuration: 2, animations: { () -> Void in
            self.backgroundImageView.alpha=1;
        }) 
        UIView.animate(withDuration: 20, animations: { () -> Void in
            self.backgroundImageView.frame = CGRect(x: -1*( 1000 - SCREEN_WIDTH )/2, y: 0, width: SCREEN_HEIGHT+500, height: SCREEN_HEIGHT+500);
        }) 
    }


    @objc func findLoginFrom1Password(){
        OnePasswordExtension.shared().findLogin(forURLString: "v2ex.com", for: self, sender: nil) { (loginDictionary, errpr) -> Void in
            if let count = loginDictionary?.count , count > 0 {
                self.userNameTextField.text = loginDictionary![AppExtensionUsernameKey] as? String
                self.passwordTextField.text = loginDictionary![AppExtensionPasswordKey] as? String

                //密码赋值后，点确认按钮
                self.loginClick(self.loginButton)
            }
        }
    }
    @objc func cancelClick (){
        self.dismiss(animated: true, completion: nil)
    }
    @objc func loginClick(_ sneder:UIButton){
        var userName:String
        var password:String
        if let len = self.userNameTextField.text?.Lenght , len > 0{
            userName = self.userNameTextField.text! ;
        }
        else{
            self.userNameTextField.becomeFirstResponder()
            return;
        }

        if let len =  self.passwordTextField.text?.Lenght , len > 0  {
            password = self.passwordTextField.text!
        }
        else{
            self.passwordTextField.becomeFirstResponder()
            return;
        }
        var code:String
        if let codeText = self.codeTextField.text, codeText.Lenght > 0 {
            code = codeText
        }
        else{
            self.codeTextField.becomeFirstResponder()
            return
        }
        
        V2BeginLoadingWithStatus("正在登录")
        if let onceStr = onceStr , let usernameStr = usernameStr, let passwordStr = passwordStr, let codeStr = codeStr {
            UserModel.Login(userName,
                            password: password,
                            once: onceStr,
                            usernameFieldName: usernameStr,
                            passwordFieldName: passwordStr ,
                            codeFieldName:codeStr,
                            code:code){
                (response:V2ValueResponse<String> , is2FALoggedIn:Bool) -> Void in
                if response.success {
                    V2Success("登录成功")
                    let username = response.value!
                    //保存下用户名
                    V2EXSettings.sharedInstance[kUserName] = username
                    
                    //将用户名密码保存进keychain （安全保存)
                    V2UsersKeychain.sharedInstance.addUser(username, password: password)
                    
                    //调用登录成功回调
                    if let handel = self.successHandel {
                        handel(username)
                    }
                    
                    //获取用户信息
                    UserModel.getUserInfoByUsername(username,completionHandler: nil)
                    self.dismiss(animated: true){
                        if is2FALoggedIn {
                            let twoFaViewController = TwoFAViewController()
                            V2Client.sharedInstance.centerViewController!.navigationController?.present(twoFaViewController, animated: true, completion: nil);
                        }
                    }
                }
                else{
                    V2Error(response.message)
                    self.refreshCode()
                }
            }
            return;
        }
        else{
            V2Error("不知道啥错误")
        }
        
    }
    
    var onceStr:String?
    var usernameStr:String?
    var passwordStr:String?
    var codeStr:String?
    @objc func refreshCode(){
        
        Alamofire.request(V2EXURL+"signin", headers: MOBILE_CLIENT_HEADERS).responseJiHtml{
            (response) -> Void in
            
            if let jiHtml = response .result.value{
                //获取帖子内容
                //取出 once 登录时要用
                
                //self.onceStr = jiHtml.xPath("//*[@name='once'][1]")?.first?["value"]
                self.usernameStr = jiHtml.xPath("//*[@id='Wrapper']/div/div[1]/div[2]/form/table/tr[1]/td[2]/input[@class='sl']")?.first?["name"]
                self.passwordStr = jiHtml.xPath("//*[@id='Wrapper']/div/div[1]/div[2]/form/table/tr[2]/td[2]/input[@class='sl']")?.first?["name"]
                self.codeStr = jiHtml.xPath("//*[@id='Wrapper']/div/div[1]/div[2]/form/table/tr[4]/td[2]/input[@class='sl']")?.first?["name"]
                
{'fraction_non_alphanumeric': 0.10091881307425817, 'fraction_numerical': 0.009790631119144449, 'mean_word_length': 1.855084927972479, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4422848', 'n_tokens_mistral': 3851, 'n_tokens_neox': 3661, 'n_words': 641}