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

import Foundation
import UIKit

class FirstStepOfRegistrationVC : StepViewController, UIPickerViewDataSource {
    
    @IBOutlet weak var screenTitle: UILabel!
    
    @IBOutlet weak var regionTitle: UILabel!
    @IBOutlet weak var abonentTitle: UILabel!
    @IBOutlet weak var emailTitle: UILabel!
    @IBOutlet weak var codeTitle: UILabel!
    
    @IBOutlet weak var regionTextField: UITextField!
    @IBOutlet weak var abonentTextField: UITextField!
    @IBOutlet weak var emailTextField: UITextField!
    @IBOutlet weak var codeTextField: UITextField!
    @IBOutlet weak var getCodeButton: UILabel!

    private var serverItems : [CallbackRegion] = []
    private var serverItem: CallbackRegion!
    private var serverNames: [String] = []
    private var gradePicker: UIPickerView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        stepNumber = 1
        gradePicker = UIPickerView()
        gradePicker.dataSource = self
        gradePicker.delegate = self
        sendRequestGetServerListId()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        localizeSubviews()
        regionTextField.setBottomBorder(Color.GrayTableCellSeparator)
        abonentTextField.setBottomBorder(Color.GrayTableCellSeparator)
        emailTextField.setBottomBorder(Color.GrayTableCellSeparator)
        codeTextField.setBottomBorder(Color.GrayTableCellSeparator)
    }

    @IBAction func nextButtonClick(sender: AnyObject) {
        
        if abonentTextField.text?.characters.count == 0 || emailTextField.text?.characters.count == 0 || codeTextField.text?.characters.count == 0 {
            AlertViewUtil.showMessageAlert(LS("registration.enter_fields"), vc: self)
            return
        }
        
        if (validateFields(true)) {
            performSegueWithIdentifier("goToSecondStep", sender: nil)
        }
    }
    
    func validateFields(code:Bool) -> Bool {
        
        var errorMessage : String = ""
        
        if !Validator.isValidAbonentID(abonentTextField.text!) {
            errorMessage += LS("registration.incorrect_abonent_id") + "\n"
        }
        
        if !Validator.isValidEmail(emailTextField.text!) {
            errorMessage += LS("registration.incorrect_email") + "\n"
        }
        
        if code && !Validator.isValidRegisterCode(codeTextField.text!) {
            errorMessage += LS("registration.incorrect_registration_code") + "\n"
        }
        
        if errorMessage != "" {
            AlertViewUtil.showMessageAlert(errorMessage, vc: self)
            return false
        } else {
            return true
        }
    }
    
    @IBAction func cancelButtonClick(sender: AnyObject) {
        navigationController?.popViewControllerAnimated(true)
    }

    private func sendRequestGetServerListId() {
//        Facade.sharedInstance().getListServerId({ (serverItems) in
//            AbonentForRegister.sharedInstance().inServerId = serverItems[0].id!
//            self.serverItems = serverItems
//            self.serverItem = serverItems[0]
//            self.serverNames = self.serverItems.map({$0.name ?? ""})
//            self.regionTextField.inputView = self.gradePicker
//            self.regionTextField.text = self.serverNames[0]
//            }, onError: { (error) in
//                print(error)
//        }) {
//            
//        }
        
        Facade.sharedInstance().getOfferRegions({ (serverItems) in
            AbonentForRegister.sharedInstance().inServerId = serverItems[0].id!
            self.serverItems = serverItems
            self.serverItem = serverItems[0]
            self.serverNames = self.serverItems.map({$0.name ?? ""})
            self.regionTextField.inputView = self.gradePicker
            self.regionTextField.text = self.serverNames[0]
            }, onError: { (error) in
                print(error)
        }) {
            
        }
    }
    
    @IBAction func getCodeButtonClicked(sender: AnyObject) {
        
        if abonentTextField.text?.characters.count == 0 || emailTextField.text?.characters.count == 0 {
            AlertViewUtil.showMessageAlert(LS("registration.enter_abonent_id_and_email"), vc: self)
            return
        }
            
        if (validateFields(false)) {
            
            AbonentForRegister.sharedInstance().inAbonentId = abonentTextField.text!
            AbonentForRegister.sharedInstance().inEmail = emailTextField.text!
            
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let myAlert = storyboard.instantiateViewControllerWithIdentifier("GetCodeViewController")
            myAlert.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext
            myAlert.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve
            self.presentViewController(myAlert, animated: true, completion: nil)
        }
    }
    
    private func localizeSubviews() {
        
    }
    
    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) {
        regionTextField.text = serverNames[row]
        self.serverItem = self.serverItems[row]
        AbonentForRegister.sharedInstance().inServerId = self.serverItem.id!
        self.view.endEditing(true)
    }
}
