//
// Created by Alexander Zalutskiy on 04.08.15.
// Copyright (c) 2015 Alexandr Zalutskiy. All rights reserved.
//
import Foundation
import UIKit
import MessageUI

class LoginViewController: ScrolledViewController, UIViewControllerTransitioningDelegate {
    
    @IBOutlet private weak var _loginButton: NextButton!
    @IBOutlet private weak var _loginTextField: UITextField!
    @IBOutlet private weak var _passwordTextField: UITextField!
    @IBOutlet private weak var _signUpButton: CancelButton!
    @IBOutlet private weak var _restorePasswordButton: HelpButton!
    @IBOutlet var lineViewBottomSpace: NSLayoutConstraint!
    @IBOutlet weak var btnPhoneNumberMode: UIButton!
    @IBOutlet weak var btnLoginMode: UIButton!
    @IBOutlet weak var lblOrMode: UILabel!
    @IBOutlet weak var showPasswordIcon: UIImageView!
    
    var isShowedAlert : Bool = false
    let defaults = NSUserDefaults.standardUserDefaults()
    var loginTryCount = 0
    var lblPrefix: UILabel?
    var isPhoneMode : Bool = true
    var keyboardShowed : Bool = false
    var passwordEnabled : Bool = false
    
    var selectedRegion: CallbackRegion?
    var cityButton: UIButton!
    static var regions: [CallbackRegion] = []
    static var regionNames: [String] = []
    
    func showError(notification: NSNotification) {
        self.processRequest(false)
    }
    
    private func registerObservers() {
                
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.updateUserInfoSuccess(_:)),
                                                         name: Facade.AbonentInfoNotificationNames.Success, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.showError(_:)),
                                                         name: AbonentInfoManager.NotificationNames.Error, object: AbonentInfoManager.sharedInstance)
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        NSNotificationCenter.defaultCenter().postNotification(NSNotification(name: Notification.loginModalClosed, object: nil))
        debugPrint("LoginViewController viewWillDisappear")
    }
    
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        print("viewDidDisappear")
    }
    
    
    private let _facade = Facade.sharedInstance()
    private let _notificationCenter = NSNotificationCenter.defaultCenter()
    
    // MARK: View life cycle
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        _loginTextField.tag = 100
        
        registerObservers()
        keyboardWillBeHidden(NSNotification(name: "some", object: nil))
        debugPrint("Login viewDidLoad begin")
        let log = XCGLogger.defaultInstance()
        log.debug("LoginWindowOpened")
        if NSUserDefaults.standardUserDefaults().boolForKey("first_opened") {
            let promoVC = storyboard?.instantiateViewControllerWithIdentifier("promo_view_controller") as! PromoViewController
            promoVC.view.translatesAutoresizingMaskIntoConstraints = false
            let views = ["promo": promoVC.view]
            view.addSubview(promoVC.view)
            view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[promo]|", options: [], metrics: nil, views: views))
            view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[promo]|", options: [], metrics: nil, views: views))
            self.addChildViewController(promoVC)
            NSUserDefaults.standardUserDefaults().setBool(false, forKey: "first_opened")
        }
        print("enabled?? \(tapGestureRecognizer.enabled)")
        _loginTextField.applyUITextFieldStyle()
        _passwordTextField.applyUITextFieldStyle()
        debugPrint("Login viewDidLoad end")
        
        let showPasswordGesture = UITapGestureRecognizer(target: self, action: #selector(LoginViewController.showPasswordEvent(_:)))
        showPasswordIcon.userInteractionEnabled = true
        showPasswordIcon.addGestureRecognizer(showPasswordGesture)
    
        
    //    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplicationWillResignActiveNotification, object: nil)
    }
    
    func showPasswordEvent(tapGestureRecognizer: UITapGestureRecognizer) {
        if passwordEnabled {
            passwordEnabled = false
            _passwordTextField.secureTextEntry = true
            showPasswordIcon.image = UIImage(named: "ic_visibility_off")
        } else {
            passwordEnabled = true
            _passwordTextField.secureTextEntry = false
            showPasswordIcon.image = UIImage(named: "ic_visibility_on")
        }
    }
    
    func keyboardWillShow(notification: NSNotification) {
//        if (keyboardShowed) {
//            return
//        }
//        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
//            self.view.frame.origin.y -= (keyboardSize.height / 2)
//        }
//        keyboardShowed = true
    }
    
    func keyboardWillHide(notification: NSNotification) {
//        if (!keyboardShowed) {
//            return
//        }
//        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
//            self.view.frame.origin.y += (keyboardSize.height / 2)
//        }
//        keyboardShowed = false
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        _loginTextField.setBottomBorder(Color.GrayTableCellSeparator)
        _passwordTextField.setBottomBorder(Color.GrayTableCellSeparator)
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
    }
    
    private func setSubviewEnabled(enabled: Bool) {
        _passwordTextField.enabled = enabled
        _loginTextField.enabled = enabled
        _loginButton.enabled = enabled
        _signUpButton.enabled = enabled
        _restorePasswordButton.enabled = enabled
    }
    
    deinit {
        _notificationCenter.removeObserver(self)
    }
    
    private func fillFieldsWithDefaultValues() {
        _loginTextField.text = UserManager.sharedInstance().login
        _passwordTextField.text = UserManager.sharedInstance().password
    }
    
    override func viewWillAppear(animated: Bool) {
        
        super.viewWillAppear(animated)
        debugPrint("Login viewWillAppear begin")
        //    navigationBarTitle = §"menu.cabinet"
        
        localizeSubviews()
        
        fillFieldsWithDefaultValues()
        self.loginTryCount = 0
        
        _loginTextField.text = "7172682610" // ntcnjdsq 7278177224
        _passwordTextField.text = "NewPassword1"
        
        let loginFieldValue = _loginTextField.text
        if containsLetters(_loginTextField.text!) {
            changeTextFieldToSymbol()
        } else {
            changeTextFieldToPhone()
        }
        _loginTextField.text = loginFieldValue
        debugPrint("Login viewWillAppear end")
    }
    
    private func RenderPrefix() {
        if (lblPrefix != nil && (_loginTextField.text?.characters.count == 0 && !_loginTextField.isFirstResponder())) {
            lblPrefix?.textColor = Color.PlaceholderGrayColor
        } else {
            lblPrefix?.textColor = Color.TitleBlackColor
        }
    }
    
    func changeTextFieldToSymbol() {
        KeyboardUtil.changeKeyboardType(UIKeyboardType.Default, textField: _loginTextField)
        isPhoneMode = false
    }
    
    func changeTextFieldToPhone() {
        isPhoneMode = true
    }
    
    func forgetPasswordSend(params: [String: AnyObject]) {
        Facade.sharedInstance().forgetPassword(params, onError: { error -> Void in
            AlertViewUtil.showErrorAlert(message: error)
            PKNotification.loading(false)
            }, onSuccess: { (email) -> Void in
                let message = String(format: LS("login.recovery.successfully_sent"), email)
                AlertViewUtil.showIncorrectAlert(message)
                PKNotification.loading(false)
        })
    }

    
    func generateRecoverAlert(recoverType: String)  {
        
        var alertTitle = ""
        var alertMessage = ""
        switch recoverType {
        case "email":
            alertTitle = LS("login.passsword_restoration.email")
            alertMessage = LS("login.alert.email.message")
            break
        case "guid":
            alertTitle = LS("login.passsword_restoration.account")
            alertMessage = LS("login.alert.account.message")
            break
        case "phone":
            alertTitle = LS("login.passsword_restoration.phone_number")
            alertMessage = LS("login.alert.phone_number.message")
            break
        default:
            break
        }
        
        var placeHolder = ""
        switch recoverType {
        case "email":
            placeHolder = LS("login.text_field.your_email.placeholder")
            break
        case "guid":
            placeHolder = LS("login.text_field.your_guid_number.placeholder")
            break
        case "phone":
            placeHolder = LS("login.text_field.your_phone_number.placeholder")
            break
        default:
            break
        }
        
        showCustomAlert(alertTitle, message: alertMessage, recoverType : recoverType, placeHolder: placeHolder)
        
    }
    
    func showCustomAlert(title : String, message : String, recoverType : String, placeHolder: String) {
        let customAlertVC = CustomAlertViewController.fromStoryboard()
        customAlertVC.fillAndShowAlert(300, height: 220, presentingVC: self.navigationController!) { (alertVC) -> Void in
            self.isShowedAlert = true
            let textField = alertVC.createTextField()
            textField.placeholder = placeHolder
            
            if recoverType == "phone" {
                textField.tag = 101
                textField.text = "+7 "
                textField.keyboardType = UIKeyboardType.NumberPad
            }
        
            alertVC.addTextField(textField)
            alertVC.addButtonHandlers({ (button) -> Void in
                }, rightButtonHandler: { (button) -> Void in
                    let textField = alertVC.textFields[0]
                    if textField.text != "" {
                        if textField.text != nil {
                            PKNotification.loading(true)
                            let params = [
                                "type": recoverType,
                                "data": self.getDataFromTextField(textField)
                                ] as [String: AnyObject]
                            self.forgetPasswordSend(params)
                        }
                        alertVC.close()
                        NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: Selector("hideShowedAlert"), userInfo: nil, repeats: false)
                    }
            })
            alertVC.addTitleAndMessage(title, msg: message)
            alertVC.addButtonTitles(rightButtonTitle: LS("login.alert.send"))
        }
    }
    
    override func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let textFieldText: NSString = textField.text ?? ""
        let txtAfterUpdate = textFieldText.stringByReplacingCharactersInRange(range, withString: string)
        
        if ( textField.tag == 101 ) {
            textField.text = (getFormattedPhone(txtAfterUpdate))
            return false
        } else {
            return true
        }
    }
    
    func getDataFromTextField(textField : UITextField) -> String {
        if ( textField.tag == 101 ) {
            return getPhoneDigits(textField.text!)
        } else {
            return textField.text!
        }
    }
    
    func hideShowedAlert() {
        self.isShowedAlert = false
    }
    
    func updateUserInfoSuccess(notification: NSNotification) {
        self.processRequest(false)
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func loginRequest(withTrimFirstSymbol : Bool) {
        if (_loginTextField.text == "") {
            AlertViewUtil.showErrorAlert(message: LS("login.type_login_or_phone"))
        } else if (_passwordTextField.text == "") {
            AlertViewUtil.showErrorAlert(message: LS("login.type_password"))
        } else {
            _loginTextField.endEditing(true)
            _passwordTextField.endEditing(true)
            if var username = _loginTextField.text, let password = _passwordTextField.text {
                
                defaults.setValue(username, forKey: "UserName")
                defaults.setValue(password, forKey: "Password")
                
                var loginType = Facade.LoginType.Login
                if containsLetters(_loginTextField.text!) {
                    loginType = Facade.LoginType.Login
                } else { //if _loginTextField.keyboardType == UIKeyboardType.PhonePad {
                    loginType = Facade.LoginType.PhoneNumber
                    username = username.stringByReplacingOccurrencesOfString("+", withString: "")
                    if (withTrimFirstSymbol) {
                        let index : String.Index = username.startIndex.advancedBy(1)
                        username = username.substringFromIndex(index)
                    }
                    Facade.phoneNumber = username
                    
                }
                self.processRequest(true)
                sendRequestLogin(username, password: password, loginType: loginType.rawValue, onSuccess: {
                    UserManager.sharedInstance().rLogin = username
                    UserManager.sharedInstance().rPassword = password
                    UserManager.sharedInstance().rLoginType = loginType.rawValue
                    self.processingLoggedInComplete()
                    }, onError: { (error) -> Void in
                        self.processingLoggedInError(error)
                })
            }
        }
        
    }
    
    func processingLoggedInComplete() {
        if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Phone {
            let mapViewControllerObj = self.storyboard?.instantiateViewControllerWithIdentifier("RootVC") as? RootVC
            self.navigationController?.pushViewController(mapViewControllerObj!, animated: true)
            self.processRequest(false)
        } else if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad {
            AbonentInfoManager.sharedInstance.updateUserInfo()
        }
    }
    
    func processingLoggedInError(error : NSError) {
        dispatch_async(dispatch_get_main_queue()) {
            if self.loginTryCount < 2 {
                self.loginTryCount += 1
                self.loginRequest(true)
            } else {
                self.loginTryCount = 0
                self.processRequest(false)
                AlertViewUtil.showErrorAlert(error.localizedDescription, vc: self)
            }
        }
    }
    
    func sendRequestLogin(userName : String, password : String, loginType : Int, onSuccess: () -> Void, onError: (NSError) -> Void) {
        _facade.login(userName, password: password, loginType: Facade.LoginType(rawValue: loginType)!, onSuccess: { () -> Void in
            onSuccess()
            }, onError: { (error) -> Void in
                onError(error)
                
            }, onFinish: {
        })
        
    }
    
    override func textFieldDidEndEditing(textField: UITextField) {
        if (textField == _loginTextField && isPhoneMode) {
            RenderPrefix();
        }
    }
    
    override func textFieldDidBeginEditing(textField: UITextField) {
        if (textField == _loginTextField && isPhoneMode) {
            lblPrefix?.textColor = Color.TitleBlackColor
        }
    }
    
    // MARK: IBActions
    
    @IBAction func btnPhoneNumberClick(sender: AnyObject) {
        btnPhoneNumberMode.selected = true
        btnLoginMode.selected = false
        changeTextFieldToPhone()
        
    }
    
    @IBAction func btnLoginModeClick(sender: AnyObject) {
        btnPhoneNumberMode.selected = false
        btnLoginMode.selected = true
        changeTextFieldToSymbol()
    }
    
    
    @IBAction func loginTextFieldEditingDidBegin(sender: UITextField) {
        
    }
    
    @IBAction func loginTextFieldClicked(sender: UITextField) {
        
    }
    
    @IBAction func restorePassword(sender: AnyObject?) {
        
        let actionSheet = UIAlertController(title: LS("login.action_sheet.title"), message: nil, preferredStyle: .ActionSheet)
        
        actionSheet.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.init(rawValue: 0)
        actionSheet.popoverPresentationController?.sourceView = self.view
        actionSheet.popoverPresentationController?.sourceRect = CGRect(origin: CGPoint(x: CGRectGetMidX(self.view.bounds), y: CGRectGetMidY(self.view.bounds)), size: CGSizeZero)
        
        actionSheet.addAction(UIAlertAction(title: LS("login.passsword_restoration.email"), style: .Default, handler: { (alertAction) in
            self.generateRecoverAlert("email")
        }))
        
        actionSheet.addAction(UIAlertAction(title: LS("login.passsword_restoration.account"), style: .Default, handler: { (alertAction) in
            
            if StepViewController.regions.isEmpty {
                SpinneredAlert.show(self)
                Facade.sharedInstance().getOfferRegions({ (callbackRegions) in
                    LoginViewController.regions = callbackRegions
                    LoginViewController.regionNames = callbackRegions.map({$0.name ?? ""})
                    self.selectedRegion = LoginViewController.regions[0]
                    self.dismissViewControllerAnimated(true, completion: nil)
                    self.showHelpAlert()
                    }, onError: { (error) in
                        
                }) {
                    
                }
            } else {
                self.showHelpAlert()
            }
        }))
        
        actionSheet.addAction(UIAlertAction(title: LS("login.passsword_restoration.phone_number"), style: .Default, handler: { (alertAction) in
            self.generateRecoverAlert("phone")
        }))
        
        actionSheet.addAction(UIAlertAction(title: LS("cancel"), style: .Cancel, handler: nil))
        
        self.presentViewController(actionSheet, animated: true, completion: nil)
        
    }
    
    
    @IBAction func login(sender: AnyObject?) {
        loginRequest(false)
    }
    
    @IBAction func register(sender: AnyObject) {
        self.performSegueWithIdentifier("registrationIntro", sender: self)
    }
    
    @IBAction func webView_touchUpInside(sender: UIButton) {
    }
    
    @IBAction func testLogin_touchUpInside(sender: UIButton) {
        
        // 7278177224
        
        _facade.login("7278177224", password: "Fvbh1988", loginType: Facade.LoginType.PhoneNumber, onSuccess: { () -> Void in
            if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Phone {
                self.performSegueWithIdentifier("loggedIn", sender: nil)
            } else if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad {
                AbonentInfoManager.sharedInstance.updateUserInfo()
                self.dismissViewControllerAnimated(true, completion: nil)
            }
            self.processRequest(false)
            }, onError: { (error) -> Void in
                dispatch_async(dispatch_get_main_queue()) {
                    self.processRequest(false)
                    AlertViewUtil.showErrorAlert(error.localizedDescription, vc: self)
                }
            }, onFinish: {
                //            self.processRequest(false)
        })
    }
    
    @IBAction func sendLogs_touchUpInside(sender: UIButton) {
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        appDelegate.sendEmailButtonTapped()
    }
    
    // MARK: Localization
    func localizeSubviews() {
        _loginTextField.placeholder = §"login.text_field.your_login.placeholder"
        _passwordTextField.placeholder = §"login.text_field.your_password.placeholder"
        let signIn = §"login.button.sign_in"
        let signUp = §"login.button.sign_up"
        let restorePassword = §"login.button.restore_password"
        
        _loginButton.setTitle(signIn, forState: .Normal)
        _signUpButton.setTitle(signUp, forState: .Normal)
        _restorePasswordButton.setTitle(restorePassword, forState: .Normal)
    }
    
    
    func showHelpAlert() {
        
        let customAlertVC = CustomAlertViewController.fromStoryboard()
        customAlertVC.fillAndShowAlert(300, height: 300, presentingVC: self, closure: { (alertVC) -> Void in
            
            customAlertVC.addTitleAndMessage("Восстановление пароля", msg: "По лицевому счету")
            customAlertVC.addButtonTitles(rightButtonTitle: "Отправить")
            
            for i in 0..<1 {
                
                let textField = alertVC.createTextField()
                var localizedId = ""
                switch i {
                case 0:
                    localizedId = "Лицевой счет"
                    break
                default:
                    break
                }
                textField.placeholder = localizedId
                customAlertVC.addTextField(textField)
            }
            
          //  KeyboardUtil.changeKeyboardType(UIKeyboardType.NumberPad, textField: alertVC.textFields[1])
            
            self.cityButton = UIButton(frame: CGRect(origin: CGPointZero, size: CGSize.zero))
            self.cityButton.setTitle(self.selectedRegion?.name ?? "", forState: .Normal)
            self.cityButton.setTitleColor(Color.BlueButtonColor, forState: .Normal)
            self.cityButton.addTarget(self, action: #selector(LoginViewController.cityButton_touchUpInside(_:)), forControlEvents: .TouchUpInside)
            self.cityButton.sizeToFit()
            
            alertVC.textFields[0].tag = 100
            
            customAlertVC.addView(self.cityButton)
            customAlertVC.addButtonHandlers({ (button) -> Void in
                
                }, rightButtonHandler: { (button) -> Void in
                    
                    let guidField = alertVC.textFields[0].text
                    let guid = self.selectedRegion?.guid_server_id!
                    let data = "\(guid!)-\(guidField!)"
                
                    if guidField == "" || self.selectedRegion == nil {
                        AlertViewUtil.showIncorrectAlert()
                    } else {
                        PKNotification.loading(true)
                        let params = [
                            "type": "guid",
                            "data": data
                            ] as [String: AnyObject]
                        print("params \(params)")
                        self.forgetPasswordSend(params)
                    }
            })
        })
        
    }
    
    func cityButton_touchUpInside(sender: UIButton) {
        let acp = ActionSheetMultipleStringPicker(title: "", rows: [LoginViewController.regionNames], initialSelection: [0], doneBlock: {
            picker, values, indexes in
            print("values = \(values)")
            print("indexes = \(indexes)")
            dispatch_async(dispatch_get_main_queue()){
                self.selectedRegion = LoginViewController.regions[values[0] as! Int]
                self.cityButton.setTitle(LoginViewController.regions[values[0] as! Int].name ?? "", forState: .Normal)
            }
            return
            }, cancelBlock: { ActionMultipleStringCancelBlock in return }, origin: sender)
        
        acp.setDoneButton(UIBarButtonItem(title: LS("ok"), style: .Plain, target: self, action: Selector()))
        acp.setCancelButton(UIBarButtonItem(title: LS("cancel"), style: .Plain, target: nil, action: Selector()))
        acp.showActionSheetPicker()
    }
    
    dynamic private func applicationWillResignActive() {
        self.view.endEditing(true)
    }

}
