<commit_before>//
//  ChatViewController.swift
//  couchbase-chat
//
//  Created by <NAME> on 10/07/15.
//  Copyright © 2015 schmid. All rights reserved.
//

import UIKit

class ChatViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var textField: UITextField!

    private var liveQuery: CBLLiveQuery?

    lazy var database: CBLDatabase = {
        let app = UIApplication.sharedApplication().delegate as! AppDelegate
        let db = app.syncHelper!.database

        db.viewNamed("messages").setMapBlock("3") { (doc, emit) in
            if let type = doc["type"] as? String where type == "message" {
                if let room = doc["room"] as? String,
                    let date = doc["created_at"] as? String,
                    let username = doc["user"] as? String,
                    let message = doc["message"] as? String {
                    emit([room, date], [username, message])
                }
            }
        }

        return db
        }()

    lazy var username: String = {
        let app = UIApplication.sharedApplication().delegate as! AppDelegate
        return app.syncHelper!.username
    }()


    var chatroomId: String? {
        didSet {
            if let chatroomId = self.chatroomId {
                chatroomDoc = database.documentWithID(chatroomId)
            }
            if editingMessage != nil {
                editingMessage = nil
            }
            self.configureView()
        }
    }
    var chatroomDoc: CBLDocument?

    var editingMessage: CBLDocument? {
        didSet {
            if let doc = editingMessage {
                self.textField.text = doc["message"] as? String
                self.textField.selectAll(nil)
                self.textField.becomeFirstResponder()
            } else {
                self.textField.text = ""
            }
        }
    }

    func configureView() {
        if let roomId = self.chatroomId,
            let chatroom = self.chatroomDoc {

            let roomname = chatroom["name"] as? String
            self.title = roomname

            if let live = liveQuery {
                live.removeObserver(self, forKeyPath: "rows")
            }

            let view = database.viewNamed("messages")
            let query = view.createQuery()
            query.startKey = [roomId]
            query.endKey = [roomId, [:]]
            let live = query.asLiveQuery()

            live.addObserver(self, forKeyPath: "rows", options: [], context: nil)

            liveQuery = live
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    deinit {
        liveQuery?.removeObserver(self, forKeyPath: "rows")
    }

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        self.tableView.reloadData()
    }

    @IBAction func sendClick(sender: UIButton) {
        sendMessage()
    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        sendMessage()

        return true
    }

    func sendMessage() {
        let text = textField.text

        if text == nil || text?.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) <= 0 {
            return
        }<commit_msg>First attempt. Does not work with the live query<commit_after>//
//  ChatViewController.swift
//  couchbase-chat
//
//  Created by <NAME> on 10/07/15.
//  Copyright © 2015 schmid. All rights reserved.
//

import UIKit

class ChatViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var textField: UITextField!

    private var liveQuery: CBLLiveQuery?

    lazy var database: CBLDatabase = {
        let app = UIApplication.sharedApplication().delegate as! AppDelegate
        let db = app.syncHelper!.database
        return db
        }()

    lazy var queryBuilder: CBLQueryBuilder = {
        let builder = CBLQueryBuilder(database: self.database, select: ["username", "message"], `where`: "type == 'message' and room = $room", orderBy: ["created_at"], error: nil)
        return builder
    }()

    lazy var username: String = {
        let app = UIApplication.sharedApplication().delegate as! AppDelegate
        return app.syncHelper!.username
    }()

    var chatroomId: String? {
        didSet {
            if let chatroomId = self.chatroomId {
                chatroomDoc = database.documentWithID(chatroomId)
            }
            if editingMessage != nil {
                editingMessage = nil
            }
            self.configureView()
        }
    }
    var chatroomDoc: CBLDocument?

    var editingMessage: CBLDocument? {
        didSet {
            if let doc = editingMessage {
                self.textField.text = doc["message"] as? String
                self.textField.selectAll(nil)
                self.textField.becomeFirstResponder()
            } else {
                self.textField.text = ""
            }
        }
    }

    func configureView() {
        if let roomId = self.chatroomId,
            let chatroom = self.chatroomDoc {

                let roomname = chatroom["name"] as? String
                self.title = roomname

                if let live = liveQuery {
                    live.removeObserver(self, forKeyPath: "rows")
                }

                let query = self.queryBuilder.createQueryWithContext(["room": roomId])
                let rows = try! query.run()
                for row in rows {
                    print(row.document)
                }
                let live = query.asLiveQuery()
                
                live.addObserver(self, forKeyPath: "rows", options: [], context: nil)
                
                liveQuery = live
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    deinit {
        liveQuery?.removeObserver(self, forKeyPath: "rows")
    }

    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        self.tableView.reloadData()
    }

    @IBAction func sendClick(sender: UIButton) {
        sendMessage()
    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        sendMessage()

        return true
    }

    func sendMessage() {
        let text = textField.text

        if text == nil || text?.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) <= 0 {
            return
        }
{'fraction_non_alphanumeric': 0.09803318992009834, 'fraction_numerical': 0.0038414259373079286, 'mean_word_length': 1.8128781331028523, 'pattern_counts': {'":': 1, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1085440', 'n_tokens_mistral': 1819, 'n_tokens_neox': 1709, 'n_words': 436}