//
//  UICreateFastPayViewController.swift
//  kt
//
//  Created by Admin on 19.12.16.
//  Copyright © 2016 SimpleCode. All rights reserved.
//

import Foundation

class UICreateFastPayViewController : KeyboardedViewController, UITableViewDelegate, UITableViewDataSource,
    UIPickerViewDelegate, UIPickerViewDataSource {
    
    //MARK: - IBOutlets
    
    @IBOutlet weak var tableView : UITableView!
    @IBOutlet weak var lblDescription : UILabel!
    @IBOutlet weak var btnDelete : UIButton!
    @IBOutlet weak var btnCreate : UIButton!
    
    @IBOutlet weak var toggle: UISegmentedControl!
    @IBOutlet weak var labelPickRegion: UILabel!
    @IBOutlet weak var regionPicker: UIPickerView!
    
    var cellsDataPhone : [TextBoxCellData] = []
    var cells : [UIBaseTableViewCell] = []
    
    var cellsDataAccount : [TextBoxCellData] = []
    var cellsAccount : [UIBaseTableViewCell] = []
    
    var cellDataName : TextBoxCellData?
    var cellDataAccountNumber : TextBoxCellData?
    var cellDataPhoneNumber : TextBoxCellData?
    var fastPayForEditing : FastPayItem?
    
    var regions : [CallbackRegion] = []
    var selectedRegion : CallbackRegion?
    
    //MARK: - System functions
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        createCells()
        
        self.regionPicker.delegate = self
        self.regionPicker.dataSource = self
        
        tableView.reloadData()
        self.title = isEditableMode() ? LS("fastPay_create_editingTitle") : LS("fastPay_create_createTitle")
        if (!isEditableMode()) {
            btnDelete.hidden = true
            btnCreate.setTitle(LS("fastPay_create_button_createTitle"), forState: UIControlState.Normal)
        } else {
            btnCreate.setTitle(LS("fastPay_create_button_saveChangesTitle"), forState: UIControlState.Normal)
            btnDelete.setTitle(LS("fastPay_create_button_deleteTitle"), forState: UIControlState.Normal)
        }
        
        toggle.setTitle(LS("createGUID_PhoneNumber_Title"), forSegmentAtIndex: 0)
        toggle.setTitle(LS("createGUID_PersonalAccount_Title"), forSegmentAtIndex: 1)
        
        labelPickRegion.text = LS("select_your_region").uppercaseString
        labelPickRegion.hidden = true
        regionPicker.hidden = true
        
        self.regionPicker.delegate = self
        self.regionPicker.dataSource = self
        
        if (isEditableMode() ) {
            if ( !self.fastPayForEditing!.isPhoneNumber() ) {
                loadAccountView()
            }
        }
        
    }
    
    
    @IBAction func onItemSelected(sender: UISegmentedControl) {
        tableView.reloadData()
        if ( toggle.selectedSegmentIndex == 0 ) {
            loadPhoneView()
        } else {
            loadAccountView()
        }
        
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.view.endEditing(true)
    }
    
    func loadPhoneView() {
        toggle.selectedSegmentIndex = 0
        labelPickRegion.hidden = true
        regionPicker.hidden = true
    }
    
    func loadAccountView() {
        toggle.selectedSegmentIndex = 1
        labelPickRegion.hidden = false
        regionPicker.hidden = false
    }
    
    //MARK: - Functions
    func createCells() {
        cells = []
        cellsAccount = []
        
        createCellsData()
        
        for var cellData in cellsDataPhone {
            let cell = tableView.dequeueReusableCellWithIdentifier(cellData.cellType.reuseIdentifier) as! UIBaseTableViewCell
            cell.fillWithCellData(cellData)
            cell.selectionStyle = .None
            cells.append(cell)
            if (cellData.cellType != .TitleValueCell) {
                cell.selectionStyle = .None
            }
        }
        for var cellData in cellsDataAccount {
            let cell = tableView.dequeueReusableCellWithIdentifier(cellData.cellType.reuseIdentifier) as! UIBaseTableViewCell
            cell.fillWithCellData(cellData)
            cell.selectionStyle = .None
            cellsAccount.append(cell)
            if (cellData.cellType != .TitleValueCell) {
                cell.selectionStyle = .None
            }
        }
    }
    
    func createCellsData() {
        cellsDataPhone = []
        cellsDataAccount = []
        
        let valueName = fastPayForEditing != nil ? fastPayForEditing!.title : ""
        cellDataName = TextBoxCellData(title: LS("fastPay_create_cardName").uppercaseString, value: valueName, placeholder: LS("fastPay_create_cellName_placeholder")) { (object) -> Bool in
            var result = false
            if (object != nil) {
                let st = object as! String
                if (st.characters.count > 0) {
                    result = true;
                }
            }
            return result
        }
        
        var accountNumber = fastPayForEditing != nil ? fastPayForEditing!.guid : ""
        accountNumber = getGuidWithoutDash(accountNumber)
        cellDataAccountNumber = TextBoxCellData(title: LS("createGUID_PersonalAccount_Title").uppercaseString, value: accountNumber, placeholder: LS("fastPay_create_cellAccountNumber_placeholder")) { (object) -> Bool in
            var result = false
            if (object != nil) {
                let st = object as! String
                if (st.characters.count > 0) {
                    result = true;
                }
            }
            return result
        }
        
        let valuePhone = fastPayForEditing != nil ? fastPayForEditing?.phoneNumber : ""
        cellDataPhoneNumber = TextBoxCellData(title: LS("fastPay_create_phoneNumber").uppercaseString, value: valuePhone!, placeholder: LS("fastPay_create_cellPhone_placeholder")) { (object) -> Bool in
            var result = false
            if (object != nil) {
                let st = object as! String
                if isValidPhoneNumber(st) {
                    result = true;
                }
            }
            return result
        }
        cellDataPhoneNumber?.keyboardType = .PhonePad
        
        cellsDataPhone.append(cellDataName!)
        cellsDataPhone.append(cellDataPhoneNumber!)
        
        cellsDataAccount.append(cellDataName!)
        cellsDataAccount.append(cellDataAccountNumber!)
        
        Facade.sharedInstance().getOfferRegions({ (regions) in
            self.regions = regions
            if (self.fastPayForEditing != nil) {
                self.scrollToUsersRegion()
            }
            self.regionPicker.reloadAllComponents()
            }, onError: { (error) in
                print(error)
        }) {
            
        }
    }
    
    func scrollToUsersRegion() {
        let regionId = getRegionFromGuid(self.fastPayForEditing!.guid);
        var index : Int = 0
        for var region in self.regions {
            if ( regionId == region.guid_server_id! ) {
                break
            }
            index += 1
        }
        if ( index >= self.regions.count ) {
            index = 0;
        }
        dispatch_async(dispatch_get_main_queue()) {
            self.regionPicker.selectRow(index, inComponent: 0, animated: true)
            self.pickerView(self.regionPicker, didSelectRow: index, inComponent: 0)
        }
    }
    
    func getRegionFromGuid(guid: String) -> String {
        var region = guid
        if let range = region.rangeOfString("-") {
            region = region.substringToIndex(range.startIndex)
        }
        return region
    }
    
    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 {
     
        if ( isPhoneNumberMode() ) {
            for var cell in cells {
                cell.updateCellData()
            }
            
            var result = true
            
            var message : String = ""
            if (!(cellDataName!.checkValues())) {
                message.appendContentsOf("\(LS("fastPay_create_validationFail_cellName")) \n")
            }
            
            if (!(cellDataPhoneNumber!.checkValues())) {
                message.appendContentsOf("\(LS("fastPay_create_validationFail_cellPhone")) \n")
            }
            
            if message.characters.count > 0 {
                result = false
                showAlert(LS("fastPay_create_alertTitle_error"), message: message)
            }
            
            return result
        } else {
            for var cell in cellsAccount {
                cell.updateCellData()
            }
            
            var result = true
            var message = ""
            
            if (!(cellDataName!.checkValues())) {
                message.appendContentsOf("\(LS("fastPay_create_validationFail_cellName")) \n")
            }
            
            if (!(cellDataAccountNumber!.checkValues())) {
                message.appendContentsOf("\(LS("fastPay_create_validationFail_accountNumber")) \n")
            }
            
            if ( selectedRegion == nil ) {
                message.appendContentsOf("\(LS("select_your_region")) \n")
            }
            
            if message.characters.count > 0 {
                result = false
                showAlert(LS("fastPay_create_alertTitle_error"), message: message)
            }
            
            if message.characters.count > 0 {
                result = false
                showAlert(LS("fastPay_create_alertTitle_error"), message: message)
            }
            
            return result
        }
    }
    
    
    func sendRequestBalance(onSuccess:() -> Void, onFailure : () -> Void) {
        Facade.sharedInstance().getBalance((cellDataPhoneNumber?.value)!, onSuccess: { (balance) in
            onSuccess()
        }) { (nsError) in
            onFailure()
        }

    }
    
    func sendRequestBalanceByGuid(onSuccess:() -> Void, onFailure : () -> Void ) {
        var guid = getGuid()
        
        Facade.sharedInstance().getBalanceByGuid( guid, onSuccess: { (balance) in
            onSuccess()
        }) { (nsError) in
            onFailure()
        }
    }
    
    func getGuid() -> String {
        return (self.selectedRegion!.guid_server_id)! + "-" + (cellDataAccountNumber?.value)!
    }
    
    
    func isEditableMode() -> Bool {
        return fastPayForEditing != nil
    }
    
    func isPhoneNumberMode() -> Bool {
        return toggle.selectedSegmentIndex == 0
    }
    
    //MARK: - IBActions
    
    @IBAction func btnCreateFastPay_action(sender: AnyObject) {
        if (checkForm()) {
            
            if ( isPhoneNumberMode() ) {
                sendRequestBalance({
                    let name = self.cellDataName?.value
                    let phoneNumber = self.cellDataPhoneNumber?.value
                    if (self.fastPayForEditing != nil) {
                        FastPayManager.sharedInstance().removeFromStoreFastPay(self.fastPayForEditing!)
                    }
                    let fastPayItem = FastPayItem(title: name!, phoneNumber: phoneNumber!)
                    FastPayManager.sharedInstance().addInStoreFastPay(fastPayItem)
                    
                    self.back()
                    }, onFailure: {
                        self.showAlert(LS("fastPay_create_alertTitle_error"), message: LS("fastPay_create_validationFail_cellPhone"))
                })
            } else {
                sendRequestBalanceByGuid(
                    {
                        print("success")
                        let name = self.cellDataName?.value
                        let guid = self.getGuid()
                        if (self.fastPayForEditing != nil) {
                            FastPayManager.sharedInstance().removeFromStoreFastPay(self.fastPayForEditing!)
                        }
                        
                        let fastPayItem = FastPayItem(title: name!, guid : guid)
                        FastPayManager.sharedInstance().addInStoreFastPay(fastPayItem)
                        
                        self.back()
                        
                    },
                    onFailure: {
                        self.showAlert(LS("fastPay_create_alertTitle_error"), message: LS("fastPay_create_validationFail_accountNumber"))
                    }
                )
            }
        }
    }
    
    func getGuidWithoutDash(input: String ) -> String {
        var guid = input
        if let range = guid.rangeOfString("-") {
            guid = guid.substringFromIndex(range.endIndex)
            
        }
        return guid
    }
    
    @IBAction func btnDeleteFastPay_action(sender: AnyObject) {
        FastPayManager.sharedInstance().removeFromStoreFastPay(self.fastPayForEditing!)
        self.back()
    }
}

//MARK: UITableViewDataSource
extension UICreateFastPayViewController {
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 70
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if ( isPhoneNumberMode() ) {
            let cell = cells[indexPath.row]
            cell.hideSeparatorLine()
            return cell
        }
        else {
            let cell = cellsAccount[indexPath.row]
            cell.hideSeparatorLine()
            return cell
        }
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if ( isPhoneNumberMode() ) {
            return cells.count
        }
        else {
            return cellsAccount.count
        }
    }
    
}

//MARK: UITableViewDelegate
extension UICreateFastPayViewController {
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print(indexPath)
    }
    
}

// UIPickerViewDelegate
extension UICreateFastPayViewController {
    // The number of columns of data
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }
    // The number of rows of data
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return self.regions.count
    }
    
    // The data to return for the row and component (column) that's being passed in
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return self.regions[row].name
    }
    
    // item has been picked
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        self.selectedRegion = regions[row]
    }
    
}

