//
//  BotViewController.swift
//  kt
//
//  Created by neox on 12.07.17.
//  Copyright © 2017 SimpleCode. All rights reserved.
//

import UIKit

class BotViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet weak var messageField: UITextField!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var circleButton: UIView!
    
    @IBOutlet weak var textFieldConstraint: NSLayoutConstraint!
    
    weak var activeField: UITextField?
    
    var messagesList : [BotResult] = []
    var heightAtIndexPath = NSMutableDictionary()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.circleButton.layer.cornerRadius = 25
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 44
        self.tableView.separatorColor = UIColor.clearColor()
        self.navigationItem.title = "Консультант"
        let tap = UITapGestureRecognizer(target: self, action: #selector(BotViewController.sendButtonTap))
        self.circleButton.userInteractionEnabled = true
        self.circleButton.addGestureRecognizer(tap)
        
        NSNotificationCenter.defaultCenter().addObserver(self,
                                                         selector: #selector(self.keyboardNotification(_:)),
                                                         name: UIKeyboardWillChangeFrameNotification,
                                                         object: nil)
        
        initializeTap()
        let results = BotManager.sharedInstance().retrieveAll()
        if results?.count > 0 {
            self.messagesList = results!
            self.tableView.reloadData()
        } else {
            addMessage("Здравствуйте! Я Ваш помощник на сайте Казахтелеком. Постараюсь ответить на большинство Ваших вопросов.", type: 0)
        }
        
    }
    
    func initializeTap() {
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(
            target: self,
            action: #selector(dismissKeyboard))
        
        view.addGestureRecognizer(tap)
    }
    
    func dismissKeyboard() {
        view.endEditing(true)
    }
    
    func keyboardNotification(notification: NSNotification) {
        if let userInfo = notification.userInfo {
            let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as?     NSValue)?.CGRectValue()
            let duration:NSTimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
            let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
            let animationCurveRaw = animationCurveRawNSN?.unsignedLongValue ?? UIViewAnimationOptions.CurveEaseInOut.rawValue
            let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw)
            if endFrame?.origin.y >= UIScreen.mainScreen().bounds.size.height {
                self.textFieldConstraint?.constant = 0.0
            } else {
                self.textFieldConstraint?.constant = endFrame?.size.height ?? 0.0
            }
            UIView.animateWithDuration(duration,
                                       delay: NSTimeInterval(0),
                                       options: animationCurve,
                                       animations: { self.view.layoutIfNeeded() },
                                       completion: nil)
        }
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        messageField.setBottomBorder(Color.GrayTableCellSeparator)
        self.tableView.scrollToBottom(true)
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    func textFieldDidBeginEditing(textField: UITextField) {
        activeField = textField
        textField.setBottomBorder(Color.BlueButtonColor)
    }
    
    func textFieldDidEndEditing(textField: UITextField) {
        activeField = nil
        textField.setBottomBorder(Color.GrayTableCellSeparator)
    }
    
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
    
    func addMessage(message: String, type: Int) {
        let botResult = BotResult.init()
        botResult.type = type
        let botNode = BotNode()
        botNode.text = message
        botNode.expanded = 0
        botNode.id = "0"
        botNode.formId = "0"
        var botNodes : [BotNode] = []
        botNodes.append(botNode)
        botResult.nodes = botNodes
        
        self.addMessage(botResult)
    }
    
    func addMessage(botResult: BotResult) {
        self.tableView.beginUpdates()
        self.messagesList.append(botResult)
        
        let indexPath = NSIndexPath(forRow: (self.messagesList.count - 1), inSection: 0)
        self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Top)
        self.tableView.endUpdates()
        
        self.tableView.scrollToBottom(true)
        
        self.persist(botResult)
    }
    
    func persist(botResult: BotResult) {
        BotManager.sharedInstance().add(botResult)
    }
    
    func reloadTable() {
        
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.messagesList.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if messagesList[indexPath.row].type == 0 {
            let cell = tableView.dequeueReusableCellWithIdentifier("BotLeftMessageCell", forIndexPath: indexPath) as! BotLeftMessageCell
            cell.bind(messagesList[indexPath.row].nodes)
            return cell
        } else {
            let cell = tableView.dequeueReusableCellWithIdentifier("BotRightMessageCell", forIndexPath: indexPath) as! BotRightMessageCell
            cell.bind(messagesList[indexPath.row].nodes)
            return cell
        }
    }
    
    func getChildNodes(id: Int) {
        Facade.sharedInstance().childBot(String(id), onSuccess: { (botResult) in
            if botResult.count != 0 {
                self.addMessage(botResult)
            } else {
                self.addMessage("Извините, по вашему запросу ничего не нашлось", type: 0)
            }
        }) { (error) in
            AlertViewUtil.showErrorAlert(error, vc: self)
        }
    }
    
    func sendButtonTap(sender:UITapGestureRecognizer) {
        if messageField.text?.characters.count == 0 {
            return
        }
        let messageStr = messageField.text!
        
        self.messageField.text = ""
        
        addMessage(messageStr, type: 1)
        
        Facade.sharedInstance().askBot(messageStr, onSuccess: { (botResult) in
            if botResult.count != 0 {
                self.addMessage(botResult)
            } else {
                self.addMessage("Извините, по вашему запросу ничего не нашлось", type: 0)
            }
        }) { (error) in
            AlertViewUtil.showErrorAlert(error, vc: self)
        }
    }
    
    func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let height = self.heightAtIndexPath.objectForKey(indexPath)
        if ((height) != nil) {
            return CGFloat(height!.floatValue)
        } else {
            return UITableViewAutomaticDimension
        }
    }
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        let height = cell.frame.size.height
        self.heightAtIndexPath.setObject(height, forKey: indexPath)
    }
    
}

extension UITableView {
    func scrollToBottom(animated: Bool = true) {
        let sections = self.numberOfSections
        let rows = self.numberOfRowsInSection(sections - 1)
        self.scrollToRowAtIndexPath(NSIndexPath(forRow: rows - 1, inSection: sections - 1), atScrollPosition: .Bottom, animated: true)
    }
}
