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

import Foundation
import UIKit

class OffersCallbackViewController: KeyboardedViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet weak var tableView: UITableView!
    
    
    private static let titleCellIdentifier = "titleCell"
    private static let fieldCellIdentifier = "fieldCell"
    private static let linkCellIdentifier = "linkCell"
    weak var activeField: UITextField?
    var params: [String: AnyObject] = [String: AnyObject]()
    //  [OffersCallbackViewController.titleCellIdentifier, "we_recall"]
    var cells:[[String]] = [[OffersCallbackViewController.titleCellIdentifier, "", notClickableCell],
                            [OffersCallbackViewController.fieldCellIdentifier, "full_name", notClickableCell],
                            [OffersCallbackViewController.fieldCellIdentifier, "phone", notClickableCell],
                            [OffersCallbackViewController.fieldCellIdentifier, "email", notClickableCell],
                            [OffersCallbackViewController.fieldCellIdentifier, "city", clickableCell],
                            [OffersCallbackViewController.linkCellIdentifier, "send", notClickableCell]]
    var fullName: String?
    var phoneNumber: String?
    var email: String?
    var region: CallbackRegion? {
        didSet {
            tableView.reloadData()
        }
    }
    var regions: [CallbackRegion] = []
    var formTypes: [FormType] = []
    
    private func configureTableView() {
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 120
    }
    
    // MARK: Keyboard action
    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)
        }
    }
    
    func keyboardWillBeHidden(notification: NSNotification) {
        tapGestureRecognizer.enabled = false
        let contentInsets = UIEdgeInsetsZero
        tableView.contentInset = contentInsets
        tableView.scrollIndicatorInsets = contentInsets
        resizeScrollViewToFitSubviews()
    }
    
    func resizeScrollViewToFitSubviews() {
        tableView.reloadData()
    }
    
    private func registerForKeyboardAction() {
        let notificationCenter = NSNotificationCenter.defaultCenter()
        notificationCenter.addObserver(self, selector: #selector(OffersCallbackViewController.keyboardDidShow(_:)),
                                       name:UIKeyboardWillShowNotification, object: nil)
        notificationCenter.addObserver(self, selector: #selector(OffersCallbackViewController.keyboardWillBeHidden(_:)),
                                       name: UIKeyboardWillHideNotification, object: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        fillTextFieldsWithDefaultValues()
        tableView.addGestureRecognizer(tapGestureRecognizer)
        registerForKeyboardAction()
        localize()
        configureTableView()
        addBackButtonForDefault(.whiteColor())
        Facade.sharedInstance().getFormType({ (formTypes) in
            self.formTypes = formTypes
            }, onError: { (error) in
                print(error)
        }) {
            
        }
        Facade.sharedInstance().getOfferRegions({ (regions) in
            self.regions = regions
            self.region = regions[0]
            self.tableView.reloadData()
            }, onError: { (error) in
                
        }) {
            
        }
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "callbackRegions" {
            //      let nav = segue.destinationViewController as! UINavigationController
            let vc = segue.destinationViewController as! OfferCalbackRegionSelectViewController
            //      let vc = nav.topViewController as! OfferCalbackRegionSelectViewController
            vc.vc = self
            vc.regions = regions
        }
    }
    
    func fillVarsFromTextViews() {
        if let fullName = params["full_name"] as? String, let phone = params["phone"] as? String, let email = params["email"] as? String where !fullName.isEmpty && !phone.isEmpty && !email.isEmpty {
            self.fullName = fullName
            self.phoneNumber = phone
            self.email = email
        }
    }
    
    
    func fillTextFieldsWithDefaultValues() {
        let abonentInfo = AbonentInfoManager.sharedInstance.abonentInfo
        if (abonentInfo != nil) {
            params["full_name"] = abonentInfo?.name
            params["phone"] = String(format:"%ld", (abonentInfo?.mobilePhone)!)
            params["email"] = abonentInfo?.email
        }
    }
    
    
}

// UITableViewDelegate
extension OffersCallbackViewController {
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == cells.count - 2 {
            performSegueWithIdentifier("callbackRegions", sender: nil)
        }
    }
}

// UITableViewDataSource
extension OffersCallbackViewController {
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        (cell as? OfferCallbackFieldCell)?.textField.setBottomBorder(Color.GrayTableCellSeparator)
        //    (cell as? SettingButtonTableViewCell)?.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 OffersCallbackViewController.titleCellIdentifier:
            let titleCell = tableView.dequeueReusableCellWithIdentifier(OffersCallbackViewController.titleCellIdentifier, forIndexPath: indexPath) as! OfferCallbackTitleCell
            cell = titleCell
            break
        case OffersCallbackViewController.fieldCellIdentifier:
            let fieldCell = tableView.dequeueReusableCellWithIdentifier(OffersCallbackViewController.fieldCellIdentifier, forIndexPath: indexPath) as! OfferCallbackFieldCell
            fieldCell.fillCell(cells[indexPath.row][1], vc: self, clickableCellValue: cells[indexPath.row][2])
            fieldCell.fillDefaultValue()
            fieldCell.RenderPrefix()
            cell = fieldCell
            break
        case OffersCallbackViewController.linkCellIdentifier:
            let linkCell = tableView.dequeueReusableCellWithIdentifier(OffersCallbackViewController.linkCellIdentifier, forIndexPath: indexPath) as! OfferCallbackLinkCell
            linkCell.fillCell(self)
            cell = linkCell
            break
        default: break
        }
        cell.selectionStyle = .None
        return cell
    }
    
}

extension OffersCallbackViewController {
    
    func cellAtTextField(textField: UITextField) -> OfferCallbackFieldCell? {
        let cell: OfferCallbackFieldCell?
        if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
            // Load resources for iOS 6.1 or earlier
            cell = textField.superview?.superview as? OfferCallbackFieldCell
        } else {
            // Load resources for iOS 7 or later
            cell = textField.superview?.superview as? OfferCallbackFieldCell
        }
        return cell;
    }
    
    func textFieldDidBeginEditing(textField: UITextField) {
        textField.setBottomBorder(Color.BlueButtonColor)
        let cell = cellAtTextField(textField);
        if let cell = cell {
            cell.ShowPrefixAsBlackColor()
            if let indexPath = tableView.indexPathForCell(cell) {
                tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Top, animated: true)
            }
        }
    }
    
    func textFieldDidEndEditing(textField: UITextField) {
        let cell = cellAtTextField(textField)
        if let cell = cell {
            cell.RenderPrefix()
        }
        textField.setBottomBorder(Color.GrayTableCellSeparator)
        activeField = nil
    }
    
}

extension OffersCallbackViewController {
    override var localizedId: String {
        return "offer_callback"
    }
}
