//
//  GetCodeViewController.swift
//  kt
//
//  Created by neox on 21.06.17.
//  Copyright © 2017 SimpleCode. All rights reserved.
//

import UIKit

class GetCodeViewController: KeyboardedViewController {
    
    @IBOutlet weak var contentView: UIView!
    @IBOutlet weak var phoneField: UITextField!
    @IBOutlet weak var iinField: UITextField!
    weak var activeField: UITextField?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        contentView.layer.cornerRadius = 6
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GetCodeViewController.keyboardWillShow(_:)), name:UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(GetCodeViewController.keyboardWillHide(_:)), name:UIKeyboardWillHideNotification, object: nil)
        self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.dismissVC(_:))))
        self.contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.nothing(_:))))
        phoneField.tag = 101
        iinField.tag = 102
    
    
    
    }
    
    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 ) {
            setPhoneNumber(getFormattedPhone(txtAfterUpdate))
            return false
        } else {
            return true
        }
    }
    
    func setPhoneNumber(phone: String) {
        phoneField.text = phone
    }
//
    func dismissVC(sender:UITapGestureRecognizer) {
        self.dismissViewControllerAnimated(true, completion: {});
    }
    
    func nothing(sender:UITapGestureRecognizer) {
        // nothing
    }
    
    func keyboardWillShow(sender: NSNotification) {
        self.view.frame.origin.y = -120
    }
    
    func keyboardWillHide(sender: NSNotification) {
        self.view.frame.origin.y = 0
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewWillAppear(animated)
        iinField.setBottomBorder(Color.GrayTableCellSeparator)
        phoneField.setBottomBorder(Color.GrayTableCellSeparator)
        setPhoneNumber("+7 ")
    }
    
    @IBAction func getCodeClicked(sender: AnyObject) {
        
        if iinField.text?.characters.count == 0 || phoneField.text?.characters.count == 0 {
            AlertViewUtil.showMessageAlert(LS("registration.enter_fields"), vc: self)
            return
        }
        
        var errorMessage : String = ""
        
        if !Validator.isValidIin(iinField.text!) {
            errorMessage += LS("registration.incorrect_iin") + "\n"
        }
        
        let phone = getPhoneDigits(phoneField.text!)
        
        if phone.characters.count != 10 {
            errorMessage += LS("registration.incorrect_phone_number") + "\n"
        }
        
        if errorMessage != "" {
            AlertViewUtil.showMessageAlert(errorMessage, vc: self)
            return
        }
        
        AbonentForRegister.sharedInstance().inIin = iinField.text!
        AbonentForRegister.sharedInstance().inPhone = phone
        
        let params: [String : String] = [
            "server_id" : AbonentForRegister.sharedInstance().inServerId,
            "abonent_id" : AbonentForRegister.sharedInstance().inAbonentId,
            "iin" : AbonentForRegister.sharedInstance().inIin,
            "email" : AbonentForRegister.sharedInstance().inEmail,
            "phone" : AbonentForRegister.sharedInstance().inPhone
        ]
        
        print(params)
        
        PKNotification.loading(true)
        
        Facade.sharedInstance().getGUID(params, onSuccess: { (message) in
            AlertViewUtil.showMessageAlert(message, vc: self, handler: {
                self.dismissViewControllerAnimated(true, completion: {});
            })
            }, onError: { (error) in
                AlertViewUtil.showErrorAlert(LS("createGUID_alert_message_checkData"), vc: self)
        }) {
            PKNotification.loading(false)
        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    func textFieldDidBeginEditing(textField: UITextField) {
        activeField = textField
        textField.setBottomBorder(Color.BlueButtonColor)
    }
    
    func textFieldDidEndEditing(textField: UITextField) {
        activeField = nil
        textField.setBottomBorder(Color.GrayTableCellSeparator)
    }
    
}
