//
//  RegistrationGUIDViewController.swift
//  kt
//
//  Created by Admin on 10.12.16.
//  Copyright © 2016 Alexandr Zalutskiy. All rights reserved.
//

import Foundation

class RegistrationGUIDViewController : UIViewController, UITableViewDelegate, UITableViewDataSource, RegionSelectViewControllerDelegate, UITextFieldTableViewCellDelegate {
    
    //MARK : - IBOutlets
    
    @IBOutlet weak var lblTitle: UILabel!
    @IBOutlet weak var lblDescription: UILabel!
    @IBOutlet weak var btnGUIDSend: UIButtonRoundedBlue!
    @IBOutlet weak var btnCancel : UIButtonRoundedGray!
    @IBOutlet weak var tableView : UITableView!
    @IBOutlet weak var scrollView : UIScrollView!
    
    //MARK : - Variables
    var activeTextField : UITextField?
    var tap: UITapGestureRecognizer?
    var cellDataIIN : TextBoxCellData?
    var cellDataPhoneNumber : TextBoxInfoCellData?
    var cellDataEMail : TextBoxCellData?
    var cellDataRegion : ServerRegionCellData?
    var cellDataPersonalAccount : TextBoxInfoCellData?
    var cellsData : [CellData] = []
    var cells : [UIBaseTableViewCell] = []
    var serverItems : [ServerItem] = []
    
    //MARK: - System
    
    override func viewDidLoad() {
        super.viewDidLoad()
        lblTitle.text = LS("createGUID_lblTitle")
        lblDescription.text = LS("createGUID_lblDescription")
        btnGUIDSend.titleLabel?.text = LS("createGUID_btnGUIDAvailable")
        btnCancel.titleLabel?.text = LS("createGUID_btnGUIDNotAvailable")
        tap = UITapGestureRecognizer(
            target: self,
            action: #selector(RegistrationGUIDViewController.dismissKeyboard))
        
        view.addGestureRecognizer(tap!)
        tap!.enabled = false;
        registerKeyboardNotifications()
        createCells()
        sendRequestGetServerListId()
        tableView.reloadData()
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "selectRegionIdentifier" {
            let vc = segue.destinationViewController as! OfferCalbackRegionSelectViewController
            vc.regions = getRegions()
            vc.delegate = self
        }
    }
    
    //MARK: Keyboard action
    
    func registerKeyboardNotifications() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidShow:", name: UIKeyboardDidShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
    }
    
    func unregisterKeyboardNotifications() {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func keyboardDidShow(notification: NSNotification) {
        tap!.enabled = true;
        // if (activeTextField != nil) {
        scrollView.setContentOffset(CGPoint(x: 0, y:50), animated: true)
        //}
    }
    
    func keyboardWillHide(notification: NSNotification) {
        tap!.enabled = true;
        scrollView.setContentOffset(CGPoint(x: 0, y:0), animated: true)
        //scrollView.contentInset = UIEdgeInsetsZero
        //scrollView.scrollIndicatorInsets = UIEdgeInsetsZero
    }
    
    
    
    //MARK: - Functions
    
    func getRegions() -> [CallbackRegion] {
        var result : [CallbackRegion] = []
        for var serverItem in serverItems {
            let region = CallbackRegion(name: serverItem.name!, id:serverItem.id!)
            result.append(region)
        }
        return result
    }
    
    func dismissKeyboard() {
        view.endEditing(true)
    }
    
    func sendRequestGetServerListId() {
        Facade.sharedInstance().getListServerId({ (serverItems) in
            self.serverItems = serverItems
            self.cellDataRegion?.serverItem = serverItems[0]
            }, onError: { (error) in
                print(error)
        }) {
            
        }
    }
    
    func sendRequestGUID(serverId : String) {
        let params: [String: AnyObject] = ["server_id": serverId,
                                           "abonent_id": (cellDataPersonalAccount?.value)!,
                                           "iin": (cellDataIIN?.value)!,
                                           "email": (cellDataEMail?.value)!,
                                           "phone": (cellDataPhoneNumber?.value)!]
        PKNotification.loading(true)
        Facade.sharedInstance().getGUID(params, onSuccess: { (message) in
            self.showAlert(LS("createGUID_alert_title_message"), message: message)
            }, onError: { (error) in
                self.showAlert("createGUID_alert_title_error", message: LS("createGUID_alert_message_checkData"))
        }) {
            PKNotification.loading(false)
        }
    }
    
    func createCells() {
        cells = []
        initCellDatas()
        for var cellData in cellsData {
            let cell = tableView.dequeueReusableCellWithIdentifier(cellData.cellType.reuseIdentifier) as! UIBaseTableViewCell
            if (cell.isKindOfClass(UITextBoxTableViewCell)) {
                let textCell = cell as! UITextBoxTableViewCell;
                textCell.delegate = self;
            }
            cell.fillWithCellData(cellData)
            cells.append(cell)
            if (cellData.cellType != .TitleValueCell) {
                cell.selectionStyle = .None
            }
        }
    }
    
    func initCellDatas() {
        cellsData = []
        cellDataIIN = TextBoxCellData(title: LS("createGUID_Iin_Title").uppercaseString,
                                      value: "",
                                      placeholder: LS("createGUID_Iin_Placeholder"),
                                      onValidate: { (object) -> Bool in
                                        var result = false
                                        if (object != nil) {
                                            let st = object as! String
                                            if isValidIIN(st) {
                                                result = true;
                                            }
                                        }
                                        return result;
                                        
        })
        cellDataIIN!.keyboardType = UIKeyboardType.DecimalPad
        
        
        cellDataPhoneNumber = TextBoxInfoCellData(title: LS("createGUID_PhoneNumber_Title").uppercaseString, value: "", placeholder: LS("createGUID_PhoneNumber_Placeholder"), onValidate: { (object) -> Bool in
            var result = false
            if (object != nil) {
                let st = object as! String
                if isValidPhoneNumber(st) {
                    result = true;
                }
            }
            return result;
            }, onClickInfo : {
                self.showAlert(LS("createGUID_alert_title_help"), message: LS("createGUID_alert_message_helpPhoneNumber"))
            }
        )
        cellDataPhoneNumber!.keyboardType = UIKeyboardType.PhonePad
        
        cellDataEMail = TextBoxCellData(title: LS("createGUID_EMail_Title").uppercaseString, value: "", placeholder: LS("createGUID_EMail_Placeholder").uppercaseString, onValidate: { (object) -> Bool in
            var result = false
            if (object != nil) {
                let st = object as! String
                if isValidEmail(st) {
                    result = true;
                }
            }
            return result;
        })
        cellDataEMail!.keyboardType = UIKeyboardType.EmailAddress
        
        cellDataRegion = ServerRegionCellData(title: LS("createGUID_Region_Title").uppercaseString, value: LS("createGUID_Region_Placeholder"), onClick: {
            self.showSelectCityTableView()
            }, onValidate: { (object) -> Bool in
                return true
        })
        
        cellDataPersonalAccount = TextBoxInfoCellData(title: LS("createGUID_PersonalAccount_Title").uppercaseString, value: "", placeholder: LS("createGUID_PersonalAccount_Placeholder"), onValidate: { (object) -> Bool in
            var result = false
            if (object != nil) {
                let st = object as! String
                if st.characters.count > 0 {
                    result = true
                }
            }
            return result;
            }, onClickInfo : {
                self.showAlert(LS("createGUID_alert_title_help"), message: LS("createGUID_alert_message_helpAccount"))
            }
        )
        cellDataPersonalAccount!.keyboardType = UIKeyboardType.DecimalPad
        cellsData.append(cellDataIIN!)
        cellsData.append(cellDataPhoneNumber!)
        cellsData.append(cellDataEMail!)
        cellsData.append(cellDataPersonalAccount!)
        cellsData.append(cellDataRegion!)
    }
    
    func showSelectCityTableView() {
        performSegueWithIdentifier("selectRegionIdentifier", sender: nil)
    }
    
    func showAlert(title : String, message: String) {
        let ac = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
        let okAction = UIAlertAction(title: LS("ok"), style: .Default, handler: nil)
        ac.addAction(okAction)
        self.presentViewController(ac, animated: true, completion: nil)
    }
    
    func checkForm() -> Bool {
        for var cell in cells {
            cell.updateCellData()
        }
        
        var result = true
        
        var message : String = ""
        if (!(cellDataIIN!.checkValues())) {
            message.appendContentsOf(LS("createGUID_alert_message_incorrectIIN"))
        }
        
        if (!(cellDataPhoneNumber!.checkValues())) {
            message.appendContentsOf(LS("createGUID_alert_message_incorrectPhoneNumber"))
        }
        
        if (!(cellDataEMail!.checkValues())) {
            message.appendContentsOf(LS("createGUID_alert_message_incorrectEMail"))
        }
        
        if (!(cellDataRegion!.checkValues())) {
            message.appendContentsOf(LS("createGUID_alert_message_incorrectRegion"))
        }
        
        if (!(cellDataPersonalAccount!.checkValues())) {
            message.appendContentsOf(LS("createGUID_alert_message_incorrectAccount"))
        }
        
        if (message.characters.count > 0) {
            result = false
            showAlert(LS("createGUID_alert_title_incorrectForm"), message: message)
        }
        
        /*guard cellDataIIN!.checkValues() && cellDataPhoneNumber!.checkValues() && cellDataEMail!.checkValues() && cellDataRegion!.checkValues() && cellDataPersonalAccount!.checkValues() else {return false}
         */
        
        return result
    }
    
    //MARK: - IBActions
    
    @IBAction func btnCancel_action(sender: AnyObject) {
        AbonentForRegister.sharedInstance().clear()
        navigationController?.popViewControllerAnimated(true)
    }
    
    @IBAction func btnSend_action(sender: AnyObject) {
        
        if (checkForm()) {
            sendRequestGUID((cellDataRegion?.serverItem!.serverId)!)
        }
    }
}

//MARK: - UITextFieldTableViewCellDelegates

extension RegistrationGUIDViewController {
    
    func textFieldDidBeginEditing(textField : UITextField, cell : UIBaseTableViewCell) {
        activeTextField = textField
    }
    
    func textFieldDidEndEditing(textField: UITextField, cell: UIBaseTableViewCell) {
        activeTextField = nil
    }
    
}

//MARK: - RegionSelectDelegates

extension RegistrationGUIDViewController {
    
    func didSelectRegion(region: CallbackRegion, index:NSNumber) {
        self.cellDataRegion?.serverItem = serverItems[(index.integerValue)]
        self.tableView.reloadData()
    }
    
}

//MARK: - UITableViewDelegates

extension RegistrationGUIDViewController {
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = tableView.cellForRowAtIndexPath(indexPath) as! UIBaseTableViewCell
        cell.cellData?.onClick()
        cell.selected = false
    }
    
}

//MARK: - UITableViewDataSource

extension RegistrationGUIDViewController {
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 75.0
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        return cells[indexPath.row]
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cells.count
    }
    
}

