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

import Foundation
import UIKit

class OnlinePaymentViewController: KeyboardedViewController, UITableViewDataSource, UITableViewDelegate {
    
    
    private static let titleCellIdentifier = "titleCell"
    private static let fieldCellIdentifier = "fieldCell"
    private static let buttonCellIdentifier = "buttonCell"
    private static let buttonFieldCellIdentifier = "buttonFieldCell"
    weak var activeField: UITextField?
    static var email:String?
    static var guidOrPhone:String?
    static var summ:String?
    static var currentPayType: String = ""
    @IBOutlet weak var tableView: UITableView!
    var params: [String: AnyObject] = [String: AnyObject]()
    let reuseCellIdentifier = "cell"
    let cells:[[String]] = [[OnlinePaymentViewController.titleCellIdentifier, "confirm_data_for_payment"],
                            [OnlinePaymentViewController.fieldCellIdentifier, "email"],
                            [OnlinePaymentViewController.buttonFieldCellIdentifier, "guid"],
                            [OnlinePaymentViewController.fieldCellIdentifier, "payment_summ"],
                            [OnlinePaymentViewController.buttonCellIdentifier, "go_payment"]]
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        localize()
        configureBlueNavbar()
    }
    
    private func registerForKeyboardAction() {
        let notificationCenter = NSNotificationCenter.defaultCenter()
        notificationCenter.addObserver(self, selector: #selector(OnlinePaymentViewController.keyboardDidShow(_:)),
                                       name:UIKeyboardWillShowNotification, object: nil)
        notificationCenter.addObserver(self, selector: #selector(OnlinePaymentViewController.keyboardWillBeHidden(_:)),
                                       name: UIKeyboardWillHideNotification, object: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.addGestureRecognizer(tapGestureRecognizer)
        registerForKeyboardAction()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(OnlinePaymentViewController.requestAbonent),
                                                         name: AbonentInfoManager.NotificationNames.Update, object: AbonentInfoManager.sharedInstance)
        if AbonentInfoManager.sharedInstance.abonentInfo != nil {
            
        } else {
            AbonentInfoManager.sharedInstance.updateUserInfo()
        }
        configureTableView()
    }
    
    func requestAbonent() {
        tableView.reloadData()
    }
    
    // MARK: Keyboard action
    func keyboardDidShow(notification: NSNotification) {
        let info = notification.userInfo!
        var kbRect = info[UIKeyboardFrameBeginUserInfoKey]!.CGRectValue
        kbRect = view.convertRect(kbRect, fromView: nil)
        
        let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0,
                                         bottom:	kbRect.height, right: 0.0)
        tableView.contentInset = contentInsets
        tableView.scrollIndicatorInsets = contentInsets
        let aRect = view.frame
        if let textField = activeField	where !CGRectContainsPoint(aRect, textField.frame.origin) {
            tableView.scrollRectToVisible(textField.frame, animated: true)
        }
        tapGestureRecognizer.enabled = true
    }
    
    func keyboardWillBeHidden(notification: NSNotification) {
        let contentInsets = UIEdgeInsetsZero
        tableView.contentInset = contentInsets
        tableView.scrollIndicatorInsets = contentInsets
        resizeScrollViewToFitSubviews()
        tapGestureRecognizer.enabled = false
    }
    
    func resizeScrollViewToFitSubviews() {
        //    OnlinePaymentViewController.textFields = [String: UITextField]()
        tableView.reloadData()
    }
    
    private func configureTableView() {
        tableView.estimatedRowHeight = 300
        tableView.rowHeight = UITableViewAutomaticDimension
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "payment_form" {
            let vc = segue.destinationViewController as! OnlinePaymentFormViewController
            vc.data = sender as? NSData
        }
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        if isBeingDismissed() || isMovingFromParentViewController() {
            clearFields()
        }
    }
    
    private func clearFields() {
        OnlinePaymentViewController.email = nil
        OnlinePaymentViewController.guidOrPhone = nil
        OnlinePaymentViewController.summ = 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 fillVarsFromTextViews() {
        OnlinePaymentViewController.email = params["email"] as? String
        OnlinePaymentViewController.summ = params["payment_summ"] as? String
        OnlinePaymentViewController.guidOrPhone = params["guid"] as? String
    }
    
    func sendOnlinePaymentRequest() {
        let request = PaymentCreateOrderRequest(payType: OnlinePaymentViewController.currentPayType, email: OnlinePaymentViewController.email, guidOrPhone: OnlinePaymentViewController.guidOrPhone, amount: OnlinePaymentViewController.summ, lang: AppLocalization.language().forTelecom)
        guard request.validateFields() else { AlertViewUtil.showAlert(request.validationMessage); return }
        self.processRequest(true)
        Facade.sharedInstance().createOrder(request.params, onSuccess: { (data) in
            self.performSegueWithIdentifier("payment_form", sender: data)
            }, onError: { (error) in
                AlertViewUtil.showIncorrectAlert(error)
            }, onFinish: {
                self.processRequest(false)
        })
        
    }
    
}

// UITableViewDataSource
extension OnlinePaymentViewController {
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        (cell as? OnlinePaymentFieldCell)?.textField.setBottomBorder(Color.GrayTableCellSeparator)
        (cell as? OnlinePaymentButtonFieldCell)?.textField.setBottomBorder(Color.GrayTableCellSeparator)
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cells.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = UITableViewCell()
        switch cells[indexPath.row][0] {
        case OnlinePaymentViewController.titleCellIdentifier:
            let titleCell = tableView.dequeueReusableCellWithIdentifier(OnlinePaymentViewController.titleCellIdentifier, forIndexPath: indexPath) as! OnlinePaymentTitleCell
            cell = titleCell
            break
        case OnlinePaymentViewController.fieldCellIdentifier:
            let fieldCell = tableView.dequeueReusableCellWithIdentifier(OnlinePaymentViewController.fieldCellIdentifier, forIndexPath: indexPath) as! OnlinePaymentFieldCell
            fieldCell.fillCell(cells[indexPath.row][1], vc: self)
            cell = fieldCell
            break
        case OnlinePaymentViewController.buttonFieldCellIdentifier:
            let buttonFieldCell = tableView.dequeueReusableCellWithIdentifier(OnlinePaymentViewController.buttonFieldCellIdentifier, forIndexPath: indexPath) as! OnlinePaymentButtonFieldCell
            buttonFieldCell.fillCell(cells[indexPath.row][1], vc: self)
            cell = buttonFieldCell
            break
        case OnlinePaymentViewController.buttonCellIdentifier:
            let buttonCell = tableView.dequeueReusableCellWithIdentifier(OnlinePaymentViewController.buttonCellIdentifier, forIndexPath: indexPath) as! OnlinePaymentButtonCell
            buttonCell.pay_touchUpInside = { () in
                self.fillVarsFromTextViews()
                if (Int(OnlinePaymentViewController.summ!)) > 100000 {
                    self.showAlert("Ограничение суммы оплаты", message: "Установлено ограничение на оплату более 100000 тг. Пожалуйста скорректируйте сумму")
                } else {
                    self.sendOnlinePaymentRequest()
                }
            }
            cell = buttonCell
            break
        default: break
        }
        //cell.selectionStyle = .None
        return cell
    }
    
}

extension OnlinePaymentViewController {
    
    func textFieldDidBeginEditing(textField: UITextField) {
        textField.setBottomBorder(Color.BlueButtonColor)
        let cell: UITableViewCell?
        
        if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
            // Load resources for iOS 6.1 or earlier
            cell = textField.superview?.superview as? UITableViewCell
            
        } else {
            // Load resources for iOS 7 or later
            cell = textField.superview?.superview?.superview as? UITableViewCell
            // TextField -> UITableVieCellContentView -> (in iOS 7!)ScrollView -> Cell!
        }
        if let cell = cell {
            if let indexPath = tableView.indexPathForCell(cell) {
                tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Top, animated: true)
            }
        }
    }
    
    func textFieldDidEndEditing(textField: UITextField) {
        textField.setBottomBorder(Color.GrayTableCellSeparator)
        activeField = nil
    }
    
}

extension OnlinePaymentViewController {
    override var localizedId: String {
        return "online_payment"
    }
}
