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

import Foundation
import UIKit

class PaymentForProviderViewController: ScrolledViewController, UITableViewDataSource, UITableViewDelegate {
  private static let titleCellIdentifier = "titleCell"
  private static let twoLabelCellIdentifier = "twoLabelCell"
  private static let fieldCellIdentifier = "fieldCell"
  private static let linkCellIdentifier = "linkCell"
  var params: [String: AnyObject] = [String: AnyObject]()
  var providersWrapper: ProvidersWrapper?
  var provider: ProvidersWrapper.Provider?
  let reuseCellIdentifier = "cell"
  var bankAndCardsDict:[String: [BankAndCard]] = [String: [BankAndCard]]() {
    didSet {
      if let banks = self.bankAndCardsDict["card_bank"] {
        self.banks = banks
      }
      if let cardTypes = self.bankAndCardsDict["card_type"] {
        self.cardTypes = cardTypes
      }
    }
  }
  var banks: [BankAndCard] = []
  var cardTypes: [BankAndCard] = []
  var selectedBank: BankAndCard?
  var selectedCardType: BankAndCard?
  
  var cells:[[String]] = [
    [PaymentForProviderViewController.twoLabelCellIdentifier, "contract_number", notClickableCell],
    [PaymentForProviderViewController.fieldCellIdentifier, "bank", clickableCell],
    [PaymentForProviderViewController.fieldCellIdentifier, "card_type", clickableCell],
    [PaymentForProviderViewController.fieldCellIdentifier, "amount", notClickableCell],
    [PaymentForProviderViewController.linkCellIdentifier, "pay", notClickableCell]]
  var contractNumber: String?
  var bank: String?
  var cardType: String?
  var amount: String?
  var providerParam: String?
  
  func fillVarsFromTextViews() {
    self.bank = params["bank"] as? String
    self.contractNumber = params["contract_number"] as? String
    //    self.cardType = params["card_type"] as? String
    self.amount = params["amount"] as? String
  }
  
  @IBOutlet weak var tableView: UITableView!
  override func viewDidLoad() {
    super.viewDidLoad()
    let request = GetCardAndBankTypes(accessToken: Facade.accessToken, clientId: Facade.clientId, serverId: Facade.serverId, abonentId: Facade.accountId)
    guard request.validateFields() else { return }
    Facade.sharedInstance().getCardAndBankTypes(request.params, onSuccess: { (bankAndCardsDict) in
      self.bankAndCardsDict = bankAndCardsDict
      }, onError: { (error) in
    }) {
      
    }
  }
  
  // MARK: Keyboard action
  override func keyboardDidShow(notification: NSNotification) {
    tapGestureRecognizer.enabled = true
    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)
    }
  }
  
  override func keyboardWillBeHidden(notification: NSNotification) {
    tapGestureRecognizer.enabled = false
    let contentInsets = UIEdgeInsetsZero
    tableView.contentInset = contentInsets
    tableView.scrollIndicatorInsets = contentInsets
    resizeScrollViewToFitSubviews()
  }
  
  override func resizeScrollViewToFitSubviews() {
    tableView.reloadData()
  }
  
  private func configureTableView() {
    tableView.estimatedRowHeight = 200
    tableView.rowHeight = UITableViewAutomaticDimension
  }
  
  private func clearFields() {
    self.contractNumber = nil
    self.bank = nil
    self.cardType = nil
    self.amount = nil
  }
  
  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    switch segue.identifier! {
    case "showBanks":
      let nav = segue.destinationViewController as! UINavigationController
      let vc = nav.topViewController as! SelectBankViewController
      vc.vc = self
      break
    case "showCardTypes":
      let nav = segue.destinationViewController as! UINavigationController
      let vc = nav.topViewController as! SelectCardTypeViewController
      vc.vc = self
      break
    default:
      break
    }
  }
  
  override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    if isBeingDismissed() || isMovingFromParentViewController() {
      clearFields()
    }
  }
  
  override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    configureBlueNavbar()
    configureTableView()
    addBackButtonForDefault(.whiteColor())
    title = provider?.name
    localizeSubviews()
  }
  
  private func localizeSubviews() {
    
  }
}

// UITableViewDelegate
extension PaymentForProviderViewController {
  func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    switch cells[indexPath.row][0] {
    case PaymentForProviderViewController.fieldCellIdentifier:
      let cell = tableView.cellForRowAtIndexPath(indexPath) as! ServicePaymentFieldCell
      cell.cellSelected()
      break
    default: break
    }
  }
}

// UITableViewDataSource
extension PaymentForProviderViewController {
  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 PaymentForProviderViewController.twoLabelCellIdentifier:
      let twoLabelCell = tableView.dequeueReusableCellWithIdentifier(PaymentForProviderViewController.twoLabelCellIdentifier, forIndexPath: indexPath) as! ServicePaymentTwoLabelCell
      twoLabelCell.fillCell(cells[indexPath.row][1], vc: self)
      cell = twoLabelCell
    case PaymentForProviderViewController.titleCellIdentifier:
      let titleCell = tableView.dequeueReusableCellWithIdentifier(PaymentForProviderViewController.titleCellIdentifier, forIndexPath: indexPath) as! ServicePaymentTitleCell
      cell = titleCell
      break
    case PaymentForProviderViewController.fieldCellIdentifier:
      let fieldCell = tableView.dequeueReusableCellWithIdentifier(PaymentForProviderViewController.fieldCellIdentifier, forIndexPath: indexPath) as! ServicePaymentFieldCell
      fieldCell.fillCell(cells[indexPath.row][1], vc: self, clickableCellValue: cells[indexPath.row][2])
      cell = fieldCell
      break
    case PaymentForProviderViewController.linkCellIdentifier:
      let linkCell = tableView.dequeueReusableCellWithIdentifier(PaymentForProviderViewController.linkCellIdentifier, forIndexPath: indexPath) as! ServicePaymentLinkCell
      linkCell.fillCell(self)
      cell = linkCell
      break
    default: break
    }
    //cell.selectionStyle = .None
    return cell
  }
  
}

extension PaymentForProviderViewController {
  override func textFieldDidBeginEditing(textField: UITextField) {
    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)
      }
    }
  }
  
  override func textFieldDidEndEditing(textField: UITextField) {
    activeField = nil
  }
  
}

extension PaymentForProviderViewController {
  override var localizedId: String {
    return "payment_for_provider"
  }
}
