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

import UIKit

class BotViewController: UIViewController {
    
    @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] = []
    
    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)
        
        addMessage("Здравствуйте! Я Ваш помощник на сайте Казахтелеком. Постараюсь ответить на большинство Ваших вопросов.", type: 0)
        
        NSNotificationCenter.defaultCenter().addObserver(self,
                                                         selector: #selector(self.keyboardNotification(_:)),
                                                         name: UIKeyboardWillChangeFrameNotification,
                                                         object: nil)
        
        initializeTap()
    }
    
    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)
    }
    
    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()
        self.tableView.scrollToBottom(true)
        return true
    }
    
    func addMessage(message: String, type: Int) {
        let botResult = BotResult()
        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.messagesList.append(botResult)
        self.tableView.reloadData()
    }
    
    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 reloadTable() {
        self.tableView.reloadData()
    }
    
    func getChildNodes(id: Int) {
        Facade.sharedInstance().childBot(String(id), onSuccess: { (botResult) in
            if botResult.count != 0 {
                self.messagesList.append(botResult)
                self.tableView.reloadData()
            } else {
                self.addMessage("Извините, по вашему запросу ничего не нашлось", type: 0)
            }
            self.tableView.scrollToBottom(true)
        }) { (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)
        self.tableView.scrollToBottom(true)
        
        Facade.sharedInstance().askBot(messageStr, onSuccess: { (botResult) in
            if botResult.count != 0 {
                self.messagesList.append(botResult)
                self.tableView.reloadData()
            } else {
                self.addMessage("Извините, по вашему запросу ничего не нашлось", type: 0)
            }
            self.tableView.scrollToBottom(true)
        }) { (error) in
            AlertViewUtil.showErrorAlert(error, vc: self)
        }
        
        //dismissKeyboard()
    }
}

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)
    }
}
