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

import Foundation
import UIKit

class OnlinePaymentViewController: UIViewController, UITextViewDelegate, 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"]]
    
    var keyboardAtOrigin = true
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        localize()
        configureBlueNavbar()
        
        tableView.delegate = self
        tableView.dataSource = self
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(OnlinePaymentViewController.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(OnlinePaymentViewController.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil)
        
    }
    
    var initialInset: UIEdgeInsets?
    
    func keyboardWillShow(notification: NSNotification) {
        if ((notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()) != nil {
            //self.view.frame.origin.y -= keyboardSize.height
            initialInset = tableView.contentInset
            
            var userInfo = notification.userInfo!
            var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
            keyboardFrame = self.view.convertRect(keyboardFrame, fromView: nil)
            
            var contentInset:UIEdgeInsets = self.tableView.contentInset
            contentInset.bottom = keyboardFrame.size.height + 30
            self.tableView.contentInset = contentInset
            
            //get indexpath
            let indexpath = NSIndexPath(forRow: 1, inSection: 0)
            self.tableView.scrollToRowAtIndexPath(indexpath, atScrollPosition: UITableViewScrollPosition.Top, animated: true)
        }
    }
    
    func keyboardWillHide(notification: NSNotification) {
        if ((notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()) != nil {
            let contentInset:UIEdgeInsets = UIEdgeInsetsZero
//            self.tableView.contentInset = contentInset
            self.tableView.contentInset = initialInset!
        }
    }
    
//    func keyboardWillShow(notification: NSNotification) {
//        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() where keyboardAtOrigin {
//            self.view.frame.origin.y -= keyboardSize.height
//            keyboardAtOrigin = false
//        }
//    }
//    
//    func keyboardWillHide(notification: NSNotification) {
//        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() where !keyboardAtOrigin {
//            self.view.frame.origin.y += keyboardSize.height
//            keyboardAtOrigin = true
//        }
//    }



    func textFieldShouldReturn(textField: UITextField) -> Bool {
        self.view.endEditing(true)
        return false
    }

//    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()
//    }
    
    func textViewShouldBeginEditing(textView: UITextView) -> Bool {
        var pointInTable:CGPoint = textView.superview!.convertPoint(textView.frame.origin, toView: tableView)
        var contentOffset:CGPoint = tableView.contentOffset
        contentOffset.y  = pointInTable.y
        if let accessoryView = textView.inputAccessoryView {
            contentOffset.y -= accessoryView.frame.size.height
        }
        tableView.contentOffset = contentOffset
        return true
    }
    
    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)
        //print(request)
        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"
    }
}
