//
//  ServiceCallbackController.swift
//  kt
//
//  Created by Alexandr Zalutskiy on 31.01.15.
//  Copyright (c) 2015 Alexandr Zalutskiy. All rights reserved.
//

import UIKit
let clickableCell = "clickableCell"
let notClickableCell = "notClickableCell"

class ServiceCallbackController: KeyboardedViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet var btnViewDogovor: UIButtonSquaredBlue!
    @IBOutlet var tableView: UITableView!


    weak var activeField: UITextField?
    private static let titleCellIdentifier = "TitleCell"
    private static let fieldCellIdentifier = "TextFieldCell"
    private static let linkCellIdentifier = "SelectCell"
    
    var params: [String: AnyObject] = [String: AnyObject]()
    
    var cells:[[String]] = [
//                            [ServiceCallbackController.titleCellIdentifier, "we_recall", notClickableCell],
                            [ServiceCallbackController.fieldCellIdentifier, "full_name", notClickableCell],
                            [ServiceCallbackController.fieldCellIdentifier, "phone", notClickableCell],
                            [ServiceCallbackController.fieldCellIdentifier, "email", notClickableCell],
                            [ServiceCallbackController.fieldCellIdentifier, "city", clickableCell]
//                            [ServiceCallbackController.linkCellIdentifier, "send", notClickableCell]
    ]
    
    var facade = Facade.sharedInstance()
    var serviceItem: ServiceItem!
    var formType: Int?
    var type: Int!
    var fullName: String?
    var phoneNumber: String?
    var email: String?
    var region: CallbackCity? {
        didSet {
            tableView.reloadData()
        }
    }
    var regions: [CallbackCity] = []
    
    @IBAction func btnViewDogovor_click(sender: AnyObject) {
        let vc = KTWebViewController(fileWithName: "IDTV", ext:"pdf")
        vc.title = "Договор"
        showViewController(vc, sender: self)
    }
    
    private func configureTableView() {
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 180
    }
    
    // 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()
    }
    
    func setTitle() {
        if type == 1 {
            title = LS("service_callback.title")
        } else {
            title = LS("service_subscribe.title")
        }
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        setTitle()
        configureBlueNavbar()
    }
    
    private func registerForKeyboardAction() {
        let notificationCenter = NSNotificationCenter.defaultCenter()
        notificationCenter.addObserver(self, selector: #selector(ServiceCallbackController.keyboardDidShow(_:)),
                                       name:UIKeyboardWillShowNotification, object: nil)
        notificationCenter.addObserver(self, selector: #selector(ServiceCallbackController.keyboardWillBeHidden(_:)),
                                       name: UIKeyboardWillHideNotification, object: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        fillTextFieldsWithDefaultValues()
        tableView.addGestureRecognizer(tapGestureRecognizer)
        registerForKeyboardAction()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ServiceCallbackController.handleRegions(_:)), name: FacadeCallbackItemsSuccess, object: facade)
        configureTableView()
        facade.citiesForCallback()
    }
    
    func isNeedShowingDogovor() -> Bool {
        return (SharedDataManager.sharedInstance().selectedServiceID == 5 || SharedDataManager.sharedInstance().selectedServiceID == 24) && type == 1
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func handleRegions(notification: NSNotification) {
        regions = notification.userInfo!["items"] as! [CallbackCity]
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "callbackRegions" {
            let nav = segue.destinationViewController as! UINavigationController
            let vc = nav.topViewController as! OfferCalbackRegionSelectViewController
            vc.serviceVC = self
        }
    }
    
    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
        }
        
    }
    
    func fillVarsFromTextViews() {
        self.fullName = params["full_name"] as? String
        self.phoneNumber = params["phone"] as? String
        self.email = params["email"] as? String
    }
    
}

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

// UITableViewDataSource
extension ServiceCallbackController {
    
    func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let myFirstLabel = UILabel()
        let myFirstButton = UIButton()
        myFirstLabel.text = "I made a label on the screen #toogood4you"
        myFirstLabel.font = UIFont(name: "MarkerFelt-Thin", size: 45)
        myFirstLabel.textColor = UIColor.redColor()
        myFirstLabel.textAlignment = .Center
        myFirstLabel.numberOfLines = 5
        myFirstLabel.frame = CGRectMake(15, 54, 300, 500)
        myFirstButton.setTitle("✸", forState: .Normal)
        myFirstButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
        myFirstButton.frame = CGRectMake(15, -50, 300, 500)
        //myFirstButton.addTarget(self, action: #selector(myClass.pressed(_:)), forControlEvents: .TouchUpInside)
        
        return myFirstButton
        //        let buttonBlue = UIButtonRoundedBlue(frame: CGRect(x:5, y: 5, width: 300, height:54))
        //        buttonBlue.titleLabel?.text = "Сформировать отчет"
        //        buttonBlue.addTarget(self, action: #selector(KTWebViewController.button_TouchUpInside(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        //        return buttonBlue
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cells.count + (isNeedShowingDogovor() ? 1 : 0)
    }
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        (cell as? CallbackTextFieldCell)?.textField.setBottomBorder(Color.GrayTableCellSeparator)
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = UITableViewCell()
        switch cells[indexPath.row][0] {
        case ServiceCallbackController.titleCellIdentifier:
            let titleCell = tableView.dequeueReusableCellWithIdentifier(ServiceCallbackController.titleCellIdentifier, forIndexPath: indexPath) as! CallbackTitleCell
            cell = titleCell
            break
        case ServiceCallbackController.fieldCellIdentifier:
            let fieldCell = tableView.dequeueReusableCellWithIdentifier(ServiceCallbackController.fieldCellIdentifier, forIndexPath: indexPath) as! CallbackTextFieldCell
            fieldCell.fillCell(cells[indexPath.row][1], vc: self, clickableCellValue: cells[indexPath.row][2])
            fieldCell.fillDefaultValue()
            fieldCell.RenderPrefix()
            cell = fieldCell
            break
        case ServiceCallbackController.linkCellIdentifier:
            let linkCell = tableView.dequeueReusableCellWithIdentifier(ServiceCallbackController.linkCellIdentifier, forIndexPath: indexPath) as! CallbackLinkCell
            linkCell.fillCell(self)
            cell = linkCell
            break
        default:
            break
        }
        cell.selectionStyle = .None
        return cell
    }
}

extension ServiceCallbackController {
    
    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
    }
    
    
    func cellAtTextField(textField: UITextField) -> CallbackTextFieldCell? {
        let cell: CallbackTextFieldCell?
        if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
            // Load resources for iOS 6.1 or earlier
            cell = textField.superview?.superview as? CallbackTextFieldCell
        } else {
            // Load resources for iOS 7 or later
            cell = textField.superview?.superview as? CallbackTextFieldCell
        }
        return cell;
    }
    
}

extension ServiceCallbackController {
    override var localizedId: String {
        return "service_callback"
    }
}
