//
//  CallbackViewController.swift
//  kt
//
//  Created by neox on 25.09.17.
//  Copyright © 2017 SimpleCode. All rights reserved.
//

import UIKit

class CallbackViewController: KeyboardedViewController, UIPickerViewDataSource, UIPickerViewDelegate {
    
    var type: Int? // 1 - COLD, 2 - HOT
    var region: String?
    var phone: String?
    var name: String?
    var region_type: String?
    var user_comment: String?
    var service_id: Int?
    var guid : String?
    var formType: Int? // 7 - mobile app
    
    weak var activeField: UITextField?
    
    @IBOutlet weak var filoField: UITextField!
    @IBOutlet weak var phoneField: UITextField!
    @IBOutlet weak var emailField: UITextField!
    @IBOutlet weak var regionField: UITextField!
    
    private var serverItems : [CallbackRegion] = []
    private var serverItem: CallbackRegion!
    private var serverNames: [String] = []
    private var gradePicker: UIPickerView!
    
    var keyboardShowed : Bool = false
    
    @IBOutlet weak var sendButton: UIButton!
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        self.navigationItem.title = LS("service.callback")//"Обратный звонок"
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CallbackViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(CallbackViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
        
        filoField.text = AbonentInfoManager.sharedInstance.abonentInfo?.name
        phoneField.text = getFormattedPhone( (AbonentInfoManager.sharedInstance.abonentInfo?.mobilePhone!.stringValue)! )
        emailField.text = AbonentInfoManager.sharedInstance.abonentInfo?.email
        
        gradePicker = UIPickerView()
        gradePicker.dataSource = self
        gradePicker.delegate = self
        
        phoneField.tag = 101
        
//        Facade.sharedInstance().getListServerId({ (serverItems) in
//            
//            self.serverItems = serverItems
//            self.serverItem = serverItems[0]
//            self.serverNames = self.serverItems.map({$0.name ?? ""})
//            self.regionField.inputView = self.gradePicker
//            self.regionField.text = self.serverNames[0]
//            
//            let serverID : Int = Facade.serverId!
//            
//            for serverModel in self.serverItems {
//                if Int(serverModel.id!)! == serverID {
//                    self.serverItem = serverModel
//                    self.regionField.text = serverModel.name
//                }
//            }
//            
//            }, onError: { (error) in
//                print(error)
//        }) {
//            
//        }
        
        Facade.sharedInstance().getOfferRegions({ (serverItems) in
            
            self.serverItems = serverItems
            self.serverItem = serverItems[0]
            self.serverNames = self.serverItems.map({$0.name ?? ""})
            self.regionField.inputView = self.gradePicker
            self.regionField.text = self.serverNames[0]
            
            let serverID : Int = Facade.serverId!
            
            print("serverID = \(serverID)")
            
            for serverModel in self.serverItems {
                if Int(serverModel.guid_server_id!)! == serverID {
                    self.serverItem = serverModel
                    self.regionField.text = serverModel.name
                }
            }
            
            }, onError: { (error) in
                print(error)
        }) {
            
        }
    }
    
    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 viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        filoField.setBottomBorder(Color.GrayTableCellSeparator)
        phoneField.setBottomBorder(Color.GrayTableCellSeparator)
        emailField.setBottomBorder(Color.GrayTableCellSeparator)
        regionField.setBottomBorder(Color.GrayTableCellSeparator)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        filoField.setBottomBorder(Color.GrayTableCellSeparator)
        phoneField.setBottomBorder(Color.GrayTableCellSeparator)
        emailField.setBottomBorder(Color.GrayTableCellSeparator)
        regionField.setBottomBorder(Color.GrayTableCellSeparator)
    }
    
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return serverNames.count
    }
    
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return serverNames[row]
    }
    
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        regionField.text = serverNames[row]
        self.serverItem = self.serverItems[row]
        self.view.endEditing(true)
    }
    
    @IBAction func sendButtonPressed(sender: AnyObject) {
        let request = ServiceCallbackRequest(cityId: self.serverItem.id, serviceId: service_id, fullName: filoField.text, phone: getPhoneDigits(phoneField.text!),
                                             email: emailField.text, type: type, formType: formType, userComment: user_comment)
        print(request.params)
        //return;
        guard request.validateFields() else {
            AlertViewUtil.showAlert(request.validationMessage);
            return }
        Facade.sharedInstance().callbackSend(request.params, onSuccess: { (msg) in
            AlertViewUtil.showAlert(msg)
            }, onError: { (error) in
                AlertViewUtil.showErrorAlert(message: error)
        }) {
        }
    }
    
    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
        }
    }
    
}


// UITextFieldDelegate
extension CallbackViewController {
    
    func textFieldDidBeginEditing(textField: UITextField) {
        activeField = textField
        textField.setBottomBorder(Color.BlueButtonColor)
    }
    
    func textFieldDidEndEditing(textField: UITextField) {
        activeField = nil
        textField.setBottomBorder(Color.GrayTableCellSeparator)
    }
}

extension Int64 {
    var stringValue:String {
        return "\(self)"
    }
}
