//
//  FourthStepOfRegistrationVC.swift
//  kt
//
//  Created by Assylkhan Rakhatov on 28.01.16.
//  Copyright © 2016 Alexandr Zalutskiy. All rights reserved.
//

import Foundation
import UIKit

class FourthStepOfRegistrationVC : StepViewController, UIPickerViewDataSource {
    
    @IBOutlet weak var phoneTitle: UILabel!
    @IBOutlet weak var questionTitle: UILabel!
    @IBOutlet weak var answerTitle: UILabel!
    
    @IBOutlet weak var phoneField: UITextField!
    @IBOutlet weak var questionField: UITextField!
    @IBOutlet weak var answerField: UITextField!
    
    @IBOutlet weak var advCheck: UISwitch!
    @IBOutlet weak var smsSwitch: UISwitch!
    
    @IBOutlet weak var registerButton: UIButtonRoundedBlue!
    @IBOutlet weak var cancelButton: UIButtonRoundedGray!
    
    private var gradePicker: UIPickerView!
    private var questionsArray: [String] = [§"registration.label.mothers_last_girl_name",
                                            §"registration.label.first_house_animal_nick",
                                            §"registration.label.birth_place",
                                            §"registration.label.childhood_street_name",
                                            §"registration.label.first_teachers_name",
                                            §"registration.label.favourite_food",
                                            §"registration.label.first_cars_mark",
                                            §"registration.label.favourite_number",
                                            §"registration.label.favourite_sport_team",
                                            §"registration.label.custom_question"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        stepNumber = 3
        gradePicker = UIPickerView()
        gradePicker.dataSource = self
        gradePicker.delegate = self
        questionField.inputView = gradePicker
        questionField.text = questionsArray[0]
        phoneField.tag = 101
        setPhoneNumber("+7 ")
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        localizeSubviews()
        phoneField.setBottomBorder(Color.GrayTableCellSeparator)
        questionField.setBottomBorder(Color.GrayTableCellSeparator)
        answerField.setBottomBorder(Color.GrayTableCellSeparator)
    }
    
    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
    }

    
    @IBAction func registerTap(sender: AnyObject) {
        
        let phone = getPhoneDigits(self.phoneField.text!)
        if phone.characters.count == 0 || answerField.text?.characters.count == 0 {
            AlertViewUtil.showMessageAlert(LS("registration.enter_fields"), vc: self)
            return;
        }
        
        if phone.characters.count != 10 {
            AlertViewUtil.showMessageAlert(LS("registration.incorrect_phone_number"), vc: self)
        }
        
        AbonentForRegister.sharedInstance().inControlQuestion = questionField.text!
        AbonentForRegister.sharedInstance().inControlAnswer = answerField.text!
        AbonentForRegister.sharedInstance().inMobile = phone
        AbonentForRegister.sharedInstance().inSms = smsSwitch.on ? 1 : 0
        AbonentForRegister.sharedInstance().inAdv = advCheck.on ? 1 : 0
        
        self.processRequest(true)
        
        Facade.sharedInstance().register({ () -> Void in
            AlertViewUtil.showMessageAlert(LS("registration.label.success"), vc: self, handler: {
                let mainStoryBoard = UIStoryboard(name: "Main", bundle: nil)
                let redViewController = mainStoryBoard.instantiateViewControllerWithIdentifier("LoginViewController") as! LoginViewController
                let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
                appDelegate.window?.rootViewController = redViewController
            })
            }, onError: { error in
                AlertViewUtil.showErrorAlert(LS("createGUID_alert_message_checkData"), vc: self)
            }, onFinish: {() in
                self.processRequest(false)
        })
    }
    
    @IBAction func backTap(sender: AnyObject) {
        navigationController?.popViewControllerAnimated(true)
    }
    
    func localizeSubviews() {
//        localizeParentSubviews()
//        answerForQuestionTextField.localizeWithParent(self, localizedId: "answer_question")
//        placeNameLabel.localizeWithParent(self, localizedId: "birth_place")
//        registerButton.setTitle(LocalizedString("registration.button.sign_up"), forState: UIControlState.Normal)
    }
    
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return questionsArray.count
    }
    
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
        return questionsArray[row]
    }
    
    func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int){
        questionField.text = questionsArray[row]
        self.view.endEditing(true)
    }
}
