<commit_before>//
//  ViewController.swift
//  Rocket.Chat.iOS
//
//  Created by <NAME> on 8/6/15.
//  Copyright © 2015 Rocket.Chat. All rights reserved.
//

import UIKit
import MMDrawerController
import ObjectiveDDP
import SwiftyJSON

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, SwitchRoomDelegate {
    
    @IBOutlet var bottomViewBottomConstraint: NSLayoutConstraint!
    @IBOutlet var tableViewTopConstraint: NSLayoutConstraint!
    
    
    @IBOutlet var mainTableview: UITableView!
    @IBOutlet var composeMsg: UITextView!
    @IBOutlet var composeMsgButton: UIButton!
    
    // indexPath to find the bottom of the tableview
    var bottomIndexPath:NSIndexPath = NSIndexPath()
    
    var dateFormatter = NSDateFormatter()
    
    var meteor: MeteorClient!
    
    //JSON to keep the response
    var chatMessages:JSON = []
    
    //Dictionary to keep each chatMessage
    var chatMessageData = [String:[ChatMessage]]()
    
    @IBOutlet var activityIndicatorInViewController: UIActivityIndicatorView!
    @IBOutlet var customIndicatorViewInViewController: UIView!
    
    var lastJoinedRoomName:String?
    var lastJoinedRoom:String?
    var tmpChatMessage:ChatMessage?
    var lastSeenTimeStamp:Double?
    
    override func viewWillAppear(animated: Bool) {
        
        if (NSUserDefaults.standardUserDefaults().valueForKey("lastJoinedRid") != nil) {
            self.lastJoinedRoomName = NSUserDefaults.standardUserDefaults().valueForKey("lastJoinedRoomName") as? String
            self.lastJoinedRoom = NSUserDefaults.standardUserDefaults().valueForKey("lastJoinedRid") as? String
        }else {
            self.lastJoinedRoomName = "general"
            self.lastJoinedRoom = "GENERAL"
        }
        
        self.title = "#\(self.lastJoinedRoomName!)"
        
        //After login join general room
        let ad = UIApplication.sharedApplication().delegate as! AppDelegate
        meteor = ad.meteorClient
        
        //Subscribe to rocketchat_message collection for the GENERAL channel
        self.meteor.addSubscription("stream-messages")

        meteor.callMethodName("channelsList", parameters: nil) { (response, error) -> Void in
            
            if error != nil {
                print(error.description)
                return
            }
            
            //print(response["result"]!["channels"]!![0]!)
        }

        meteor.callMethodName("joinDefaultChannels", parameters: []) { (response, error) -> Void in
            
            if error != nil {
                print("Error:\(error.description)")
                return
            }else{
                
                //Add observer to handle incoming messages
                NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveUpdate:", name: "stream-messages_added", object: nil)

            }
        }

        //Get last 50 messages
        loadHistory(self.lastJoinedRoom!, numberOfMessages: 50)

        //Get the leftViewController instance and use it to notify this ViewController about changing the channel using the SwitchRoomDelegate
        let leftNavController = ad.centerContainer?.leftDrawerViewController as! UINavigationController
        let leftViewController = leftNavController.viewControllers.first as! LeftViewController
        leftViewController.viewController = self
        
    }
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Notifications to manage keyboard
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWasShown:"), name:UIKeyboardWillShowNotification, object: nil);
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);
        
        // Create tap gesture
        let tapGesture = UITapGestureRecognizer(target: self, action: Selector("dismissKeyboard"))
        tapGesture.cancelsTouchesInView = true
        
        //Create double tap gesture
        let doubleTapGesture = UITapGestureRecognizer(target: self, action: Selector("showHiddenTimestamp:"))
        doubleTapGesture.numberOfTapsRequired = 2

        //Add gestures on tableview
        mainTableview.addGestureRecognizer(tapGesture)
        mainTableview.addGestureRecognizer(doubleTapGesture)

        
        //Remove lines between cells
        mainTableview.separatorStyle = UITableViewCellSeparatorStyle.None
        
        mainTableview.rowHeight = UITableViewAutomaticDimension
        mainTableview.estimatedRowHeight = 75
 
        //Set border to composeMsg textarea
        composeMsg.layer.borderColor = UIColor.blackColor().CGColor
        composeMsg.layer.borderWidth = 0.5
        composeMsg.layer.cornerRadius = 10
        
        dateFormatter.dateFormat = "HH:mm"
        
        self.tmpChatMessage?.messageType = ""
    }
        
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    @IBAction func leftNavTapped(sender: AnyObject) {
        
        //get the appDelegate
        let appdelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        
        //Toggle the drawer to the left
        appdelegate.centerContainer?.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: nil)
        <commit_msg>Moved viewWillAppear function's code to viewDidLoad and remove viewWillAppear function because that code loads every time view appears and we don't want that. Also it was causing some issues.<commit_after>//
//  ViewController.swift
//  Rocket.Chat.iOS
//
//  Created by <NAME> on 8/6/15.
//  Copyright © 2015 Rocket.Chat. All rights reserved.
//

import UIKit
import MMDrawerController
import ObjectiveDDP
import SwiftyJSON

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, SwitchRoomDelegate {
    
    @IBOutlet var bottomViewBottomConstraint: NSLayoutConstraint!
    @IBOutlet var tableViewTopConstraint: NSLayoutConstraint!
    
    
    @IBOutlet var mainTableview: UITableView!
    @IBOutlet var composeMsg: UITextView!
    @IBOutlet var composeMsgButton: UIButton!
    
    // indexPath to find the bottom of the tableview
    var bottomIndexPath:NSIndexPath = NSIndexPath()
    
    var dateFormatter = NSDateFormatter()
    
    var meteor: MeteorClient!
    
    //JSON to keep the response
    var chatMessages:JSON = []
    
    //Dictionary to keep each chatMessage
    var chatMessageData = [String:[ChatMessage]]()
    
    @IBOutlet var activityIndicatorInViewController: UIActivityIndicatorView!
    @IBOutlet var customIndicatorViewInViewController: UIView!
    
    var lastJoinedRoomName:String?
    var lastJoinedRoom:String?
    var tmpChatMessage:ChatMessage?
    var lastSeenTimeStamp:Double?
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Notifications to manage keyboard
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWasShown:"), name:UIKeyboardWillShowNotification, object: nil);
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);
        
        // Create tap gesture
        let tapGesture = UITapGestureRecognizer(target: self, action: Selector("dismissKeyboard"))
        tapGesture.cancelsTouchesInView = true
        
        //Create double tap gesture
        let doubleTapGesture = UITapGestureRecognizer(target: self, action: Selector("showHiddenTimestamp:"))
        doubleTapGesture.numberOfTapsRequired = 2

        //Add gestures on tableview
        mainTableview.addGestureRecognizer(tapGesture)
        mainTableview.addGestureRecognizer(doubleTapGesture)

        
        //Remove lines between cells
        mainTableview.separatorStyle = UITableViewCellSeparatorStyle.None
        
        mainTableview.rowHeight = UITableViewAutomaticDimension
        mainTableview.estimatedRowHeight = 75
 
        //Set border to composeMsg textarea
        composeMsg.layer.borderColor = UIColor.blackColor().CGColor
        composeMsg.layer.borderWidth = 0.5
        composeMsg.layer.cornerRadius = 10
        
        dateFormatter.dateFormat = "HH:mm"
        
        self.tmpChatMessage?.messageType = ""
        
        
        
        if (NSUserDefaults.standardUserDefaults().valueForKey("lastJoinedRid") != nil) {
            self.lastJoinedRoomName = NSUserDefaults.standardUserDefaults().valueForKey("lastJoinedRoomName") as? String
            self.lastJoinedRoom = NSUserDefaults.standardUserDefaults().valueForKey("lastJoinedRid") as? String
        }else {
            self.lastJoinedRoomName = "general"
            self.lastJoinedRoom = "GENERAL"
        }
        
        self.title = "#\(self.lastJoinedRoomName!)"
        
        //After login join general room
        let ad = UIApplication.sharedApplication().delegate as! AppDelegate
        meteor = ad.meteorClient
        
        //Subscribe to rocketchat_message collection for the GENERAL channel
        self.meteor.addSubscription("stream-messages")
        
        
        meteor.callMethodName("channelsList", parameters: nil) { (response, error) -> Void in
            
            if error != nil {
                print(error.description)
                return
            }
            
            //print(response["result"]!["channels"]!![0]!)
        }
        
        meteor.callMethodName("joinDefaultChannels", parameters: []) { (response, error) -> Void in
            
            if error != nil {
                print("Error:\(error.description)")
                return
            }else{
                
                //Add observer to handle incoming messages
                NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveUpdate:", name: "stream-messages_added", object: nil)
                
            }
        }
        
        //Get last 50 messages
        loadHistory(self.lastJoinedRoom!, numberOfMessages: 50)
        
        
        //Get the leftViewController instance and use it to notify this ViewController about changing the channel using the SwitchRoomDelegate
        let leftNavController = ad.centerContainer?.leftDrawerViewController as! UINavigationController
        let leftViewController = leftNavController.viewControllers.first as! LeftViewController
        leftViewController.viewController = self
        
        
    }
        
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    @IBAction func leftNavTapped(sender: AnyObject) {
        
        //get the appDelegate
        let appdelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        
        //Toggle the drawer to the left
        appdelegate.centerContainer?.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: nil)
        
{'fraction_non_alphanumeric': 0.07772113406672033, 'fraction_numerical': 0.0035774975404704408, 'mean_word_length': 2.57595139110969, 'pattern_counts': {'":': 0, '<': 5, '<?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': '5445887', 'n_tokens_mistral': 3031, 'n_tokens_neox': 2858, 'n_words': 670}