<commit_before>//
//  MainVCMethods.swift
//  Susi
//
//  Created by <NAME> on 2017-06-04.
//  Copyright © 2017 FOSSAsia. All rights reserved.
//

import UIKit
import CoreLocation
import Popover
import RSKGrowingTextView

extension MainViewController {

    func subscribeToKeyboardNotifications() {
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    func handleKeyboardNotification(notification: NSNotification) {

        if let userInfo = notification.userInfo {

            let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue
            let isKeyboardShowing = notification.name == NSNotification.Name.UIKeyboardWillShow

            bottomConstraintTextView?.constant = isKeyboardShowing ? (-keyboardFrame!.height - 8.0) : 0
            bottomConstraintSendButton?.constant = isKeyboardShowing ? (-keyboardFrame!.height - 8.0) : 0

            collectionView?.frame = isKeyboardShowing ? CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height - keyboardFrame!.height - 47) :
                CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height - 47)

            UIView.animate(withDuration: 0, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: {

                self.view.layoutIfNeeded()

            }, completion: { (_) in

                if isKeyboardShowing {
                    self.scrollToLast()
                }

            })
        }
    }

    // Resign responders
    func resignResponders() {
        self.view.endEditing(true)
    }

    // Configures Location Manager
    func configureLocationManager() {
        locationManager.delegate = self
        if CLLocationManager.authorizationStatus() == .notDetermined || CLLocationManager.authorizationStatus() == .denied {
            self.locationManager.requestWhenInUseAuthorization()
        }

        locationManager.distanceFilter = kCLDistanceFilterNone
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()
    }

    // Setup Navigation Bar
    func setupTitle() {
        navigationItem.title = ControllerConstants.susiTitle
        navigationItem.titleLabel.textAlignment = .left
        navigationItem.titleLabel.textColor = .white

        navigationItem.rightViews = [searchButton, settingsButton]
    }

    // Setup View
    func setupView() {
        self.view.backgroundColor = UIColor.rgb(red: 236, green: 229, blue: 221)
    }

    // Setup Settings View
    func showSettingsView() {
        let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: Int(self.view.frame.width / 2), height: (ControllerConstants.Settings.settingsList.count * 44)))
        tableView.delegate = self
        tableView.dataSource = self
        tableView.isScrollEnabled = false
        self.popover = Popover(options: self.popoverOptions)
        self.popover.show(tableView, fromView: settingsButton)
    }

    // Shows Youtube Player
    func addYotubePlayer(_ videoID: String) {
        if let window = UIApplication.shared.keyWindow {
            blackView.frame = window.frame
            self.view.addSubview(blackView)
            blackView.backgroundColor = UIColor(white: 0, alpha: 0.5)
            blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleDismiss)))

            self.blackView.addSubview(self.youtubePlayer)
            let centerX = UIScreen.main.bounds.size.width / 2
            let centerY = UIScreen.main.bounds.size.height / 3
            self.youtubePlayer.center = CGPoint(x: centerX, y: centerY)
            self.youtubePlayer.loadVideoID(videoID)

            blackView.alpha = 0
            youtubePlayer.alpha = 0

            UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
                self.blackView.alpha = 1
                self.youtubePlayer.alpha = 1
            }, completion: nil)
        }
    }

    func handleDismiss() {

        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
            self.blackView.removeFromSuperview()
        }, completion: nil)

    }

    // Setup Collection View
    func setupCollectionView() {
        // Check if user defaults have an image, set background as image
        if let userDefaultData = getWallpaperFromUserDefaults() {
            if let imageData = userDefaultData as? Data { // Check if object saved in user defaults if of type Data
                setBackgroundImage(image: UIImage(data : imageData))
            }
        }
        collectionView?.backgroundColor = .clear
        collectionView?.delegate = self
        collectionView?.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height - 47)
        collectionView?.register(IncomingBubbleCell.self, forCellWithReuseIdentifier: ControllerConstants.incomingCell)
        collectionView?.register(OutgoingChatCell.self, forCellWithReuseIdentifier: ControllerConstants.outgoingCell)
    }

    // Send Button Action
    func handleSend() {
        if let text = inputTextView.text, text.characters.count > 0 {
            if text.contains(ControllerConstants.play) || text.contains(ControllerConstants.play.uppercased()) {

                let query = text.replacingOccurrences(of: ControllerConstants.play, with: "")
                    .replacingOccurrences(of: ControllerConstants.play.uppercased(), with: "")

                Client.sharedInstance.searchYotubeVideos(query) { (result, _, _) in
                    DispatchQueue.main.async {
                        if let result = result {
                            self.addYotubePlayer(result)
                        }
                    }
                }

            } else {

                var params: [String : AnyObject] = [
                    Client.WebsearchKeys.Query: inputTextView.text! as AnyObject,
                    Client.ChatKeys.TimeZoneOffset: ControllerConstants.timeZone as AnyObject,
                    Client.ChatKeys.Language: Locale.current.languageCode as AnyObject
                ]

                if let location = locationManager.location {
                    params[Client.ChatKeys.Latitude] = location.coordinate.latitude as AnyObject
                    params[Client.ChatKeys.Longitude] = location.coordinate.longitude as AnyObject
                }

                Client.sharedInstance.queryResponse(params) { (results, success, _) in
                    DispatchQueue.main.async {
                        if success {
                            self.messages.append(results!)
                            let indexPath = IndexPath(item: self.messages.count - 1, section: 0)
                            self.collectionView?.insertItems(at: [indexPath])
                        }
                        self.scrollToLast()
                    }
                }
            }
        }
        saveMessage()
    }

    // Setup Input Components
    func setupInputComponents() {

        view.addSubview(inputTextView)
        view.addSubview(sendButton)

        view.layout(sendButton).bottomRight(bottom: 8.0, right: 8.0).width(44).height(44)
        view.layout(inputTextView).bottomLeft(bottom: 8.0, left: 8.0).width(view.frame.width - 64)

        bottomConstraintTextView = NSLayoutConstraint(item: inputTextView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0)<commit_msg>Fix: remove hardcoded video play (#93)<commit_after>//
//  MainVCMethods.swift
//  Susi
//
//  Created by <NAME> on 2017-06-04.
//  Copyright © 2017 FOSSAsia. All rights reserved.
//

import UIKit
import CoreLocation
import Popover
import RSKGrowingTextView

extension MainViewController {

    func subscribeToKeyboardNotifications() {
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    func handleKeyboardNotification(notification: NSNotification) {

        if let userInfo = notification.userInfo {

            let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue
            let isKeyboardShowing = notification.name == NSNotification.Name.UIKeyboardWillShow

            bottomConstraintTextView?.constant = isKeyboardShowing ? (-keyboardFrame!.height - 8.0) : 0
            bottomConstraintSendButton?.constant = isKeyboardShowing ? (-keyboardFrame!.height - 8.0) : 0

            collectionView?.frame = isKeyboardShowing ? CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height - keyboardFrame!.height - 47) :
                CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height - 47)

            UIView.animate(withDuration: 0, delay: 0, options: UIViewAnimationOptions.curveEaseOut, animations: {

                self.view.layoutIfNeeded()

            }, completion: { (_) in

                if isKeyboardShowing {
                    self.scrollToLast()
                }

            })
        }
    }

    // Resign responders
    func resignResponders() {
        self.view.endEditing(true)
    }

    // Configures Location Manager
    func configureLocationManager() {
        locationManager.delegate = self
        if CLLocationManager.authorizationStatus() == .notDetermined || CLLocationManager.authorizationStatus() == .denied {
            self.locationManager.requestWhenInUseAuthorization()
        }

        locationManager.distanceFilter = kCLDistanceFilterNone
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()
    }

    // Setup Navigation Bar
    func setupTitle() {
        navigationItem.title = ControllerConstants.susiTitle
        navigationItem.titleLabel.textAlignment = .left
        navigationItem.titleLabel.textColor = .white

        navigationItem.rightViews = [searchButton, settingsButton]
    }

    // Setup View
    func setupView() {
        self.view.backgroundColor = UIColor.rgb(red: 236, green: 229, blue: 221)
    }

    // Setup Settings View
    func showSettingsView() {
        let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: Int(self.view.frame.width / 2), height: (ControllerConstants.Settings.settingsList.count * 44)))
        tableView.delegate = self
        tableView.dataSource = self
        tableView.isScrollEnabled = false
        self.popover = Popover(options: self.popoverOptions)
        self.popover.show(tableView, fromView: settingsButton)
    }

    // Shows Youtube Player
    func addYotubePlayer(_ videoID: String) {
        if let window = UIApplication.shared.keyWindow {
            blackView.frame = window.frame
            self.view.addSubview(blackView)
            blackView.backgroundColor = UIColor(white: 0, alpha: 0.5)
            blackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleDismiss)))

            self.blackView.addSubview(self.youtubePlayer)
            let centerX = UIScreen.main.bounds.size.width / 2
            let centerY = UIScreen.main.bounds.size.height / 3
            self.youtubePlayer.center = CGPoint(x: centerX, y: centerY)
            self.youtubePlayer.loadVideoID(videoID)

            blackView.alpha = 0
            youtubePlayer.alpha = 0

            UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
                self.blackView.alpha = 1
                self.youtubePlayer.alpha = 1
            }, completion: nil)
        }
    }

    func handleDismiss() {

        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
            self.blackView.removeFromSuperview()
        }, completion: nil)

    }

    // Setup Collection View
    func setupCollectionView() {
        // Check if user defaults have an image, set background as image
        if let userDefaultData = getWallpaperFromUserDefaults() {
            if let imageData = userDefaultData as? Data { // Check if object saved in user defaults if of type Data
                setBackgroundImage(image: UIImage(data : imageData))
            }
        }
        collectionView?.backgroundColor = .clear
        collectionView?.delegate = self
        collectionView?.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height - 47)
        collectionView?.register(IncomingBubbleCell.self, forCellWithReuseIdentifier: ControllerConstants.incomingCell)
        collectionView?.register(OutgoingChatCell.self, forCellWithReuseIdentifier: ControllerConstants.outgoingCell)
    }

    // Send Button Action
    func handleSend() {
        if let text = inputTextView.text, text.characters.count > 0 {
            var params: [String : AnyObject] = [
                Client.WebsearchKeys.Query: inputTextView.text! as AnyObject,
                Client.ChatKeys.TimeZoneOffset: ControllerConstants.timeZone as AnyObject,
                Client.ChatKeys.Language: Locale.current.languageCode as AnyObject
            ]

            if let location = locationManager.location {
                params[Client.ChatKeys.Latitude] = location.coordinate.latitude as AnyObject
                params[Client.ChatKeys.Longitude] = location.coordinate.longitude as AnyObject
            }

            Client.sharedInstance.queryResponse(params) { (results, success, _) in
                DispatchQueue.main.async {
                    if success {
                        self.messages.append(results!)
                        let indexPath = IndexPath(item: self.messages.count - 1, section: 0)
                        self.collectionView?.insertItems(at: [indexPath])
                    }
                    self.scrollToLast()
                }
            }
        }
        saveMessage()
    }

    // Setup Input Components
    func setupInputComponents() {

        view.addSubview(inputTextView)
        view.addSubview(sendButton)

        view.layout(sendButton).bottomRight(bottom: 8.0, right: 8.0).width(44).height(44)
        view.layout(inputTextView).bottomLeft(bottom: 8.0, left: 8.0).width(view.frame.width - 64)

        bottomConstraintTextView = NSLayoutConstraint(item: inputTextView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1, constant: 0)
{'fraction_non_alphanumeric': 0.0917706734298872, 'fraction_numerical': 0.011346192351331509, 'mean_word_length': 2.401589103291714, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, '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': '4819742', 'n_tokens_mistral': 4189, 'n_tokens_neox': 3856, 'n_words': 831}