<commit_before>//
//  NewRoomViewController.swift
//  Rocket.Chat
//
//  Created by <NAME> on 27/09/17.
//  Copyright © 2017 Rocket.Chat. All rights reserved.
//

import UIKit
import RealmSwift

class NewRoomViewController: BaseViewController {

    let tableViewData: [SectionForm] = [
        SectionForm(
            name: nil,
            footer: nil,
            cells: [
                FormCell(
                    cell: .check(title: localized("new_room.cell.public_channel.title"), description: localized("new_room.cell.public_chanell.description")),
                    key: "public room",
                    defaultValue: true
                ),
                FormCell(
                    cell: .check(title: localized("new_room.cell.read_only.title"), description: localized("new_room.cell.read_only.description")),
                    key: "read only room",
                    defaultValue: false
                )
            ]
        ),
        SectionForm(
            name: localized("new_room.group.channel.name"),
            footer: localized("new_room.group.channel.footer"),
            cells: [
                FormCell(
                    cell: .textField(placeholder: localized("new_room.cell.channel_name.title"), icon: #imageLiteral(resourceName: "Hashtag")),
                    key: "room name",
                    defaultValue: ""
                )
            ]
        )
    ]

    var referenceOfCells: [String: FormTableViewCellProtocol] = [:]
    lazy var setValues: [String: Any] = {
        return tableViewData.reduce([String: Any]()) { (dict, entry) in
            var ndict = dict
            entry.cells.forEach { ndict[$0.key] = $0.defaultValue }
            return ndict
        }
    }()

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        CheckTableViewCell.registerCell(for: tableView)
        TextFieldTableViewCell.registerCell(for: tableView)
    }

    fileprivate func showErrorAlert(_ errorMessage: String?) {
        let errorMessage = errorMessage ?? localized("error.socket.default_error_message")

        let alert = UIAlertController(
            title: localized("error.socket.default_error_title"),
            message: errorMessage,
            preferredStyle: .alert
        )
        alert.addAction(UIAlertAction(title: localized("global.ok"), style: .default, handler: nil))
        DispatchQueue.main.sync {
            self.present(alert, animated: true, completion: nil)
        }
    }

    @IBAction func buttonCreateDidPressed(_ sender: UIButton) {
        guard let roomName = setValues["room name"] as? String else { return }
        guard let publicRoom = setValues["public room"] as? Bool else { return }
        guard let readOnlyRoom = setValues["read only room"] as? Bool else { return }

        let roomType: RoomCreateType
        if publicRoom {
            roomType = .channel
        } else {
            roomType = .group
        }

        sender.isEnabled = false
        executeRequestCreateRoom(roomName: roomName, roomType: roomType, readOnlyRoom: readOnlyRoom) { [weak self] success, errorMessage in

            if success {
                self?.dismiss(animated: true, completion: nil)
            } else {
                self?.showErrorAlert(errorMessage)
                sender.isEnabled = true
            }
        }
    }

    fileprivate func executeRequestCreateRoom(roomName: String, roomType: RoomCreateType, readOnlyRoom: Bool, completion: @escaping (Bool, String?) -> Void) {
        API.shared.fetch(RoomCreateRequest(roomName: roomName, type: roomType, readOnly: readOnlyRoom)) { result in

            guard let success = result?.raw?["success"].boolValue,
                success == true else {
                    completion(false, result?.raw?["error"].string)
                    return
            }

            guard let auth = AuthManager.isAuthenticated() else { return }

            SubscriptionManager.updateSubscriptions(auth) { _ in
                if let findNewRoom = Realm.shared?.objects(Subscription.self).filter("name == '\(roomName)'").first {
                    let newRoom = findNewRoom

                    let controller = ChatViewController.shared
                    controller?.subscription = newRoom

                    completion(true, nil)
                } else {
                    completion(false, nil)
                }
            }
        }
    }

    @IBAction func buttonCloseDidPressed(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
}

// MARK: FormTableViewDelegate

extension NewRoomViewController: FormTableViewDelegate {
    func updateDictValue(key: String, value: Any) {
        setValues[key] = value

        if key == "public room",
            let value = value as? Bool,
            let cellRoomName = referenceOfCells["room name"] as? TextFieldTableViewCell {

            if value {<commit_msg>Small fix. If we create a room with same name of user that we have a direct message openped, the direct message will open instead of the new room created.<commit_after>//
//  NewRoomViewController.swift
//  Rocket.Chat
//
//  Created by <NAME> on 27/09/17.
//  Copyright © 2017 Rocket.Chat. All rights reserved.
//

import UIKit
import RealmSwift

class NewRoomViewController: BaseViewController {

    let tableViewData: [SectionForm] = [
        SectionForm(
            name: nil,
            footer: nil,
            cells: [
                FormCell(
                    cell: .check(title: localized("new_room.cell.public_channel.title"), description: localized("new_room.cell.public_chanell.description")),
                    key: "public room",
                    defaultValue: true
                ),
                FormCell(
                    cell: .check(title: localized("new_room.cell.read_only.title"), description: localized("new_room.cell.read_only.description")),
                    key: "read only room",
                    defaultValue: false
                )
            ]
        ),
        SectionForm(
            name: localized("new_room.group.channel.name"),
            footer: localized("new_room.group.channel.footer"),
            cells: [
                FormCell(
                    cell: .textField(placeholder: localized("new_room.cell.channel_name.title"), icon: #imageLiteral(resourceName: "Hashtag")),
                    key: "room name",
                    defaultValue: ""
                )
            ]
        )
    ]

    var referenceOfCells: [String: FormTableViewCellProtocol] = [:]
    lazy var setValues: [String: Any] = {
        return tableViewData.reduce([String: Any]()) { (dict, entry) in
            var ndict = dict
            entry.cells.forEach { ndict[$0.key] = $0.defaultValue }
            return ndict
        }
    }()

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        CheckTableViewCell.registerCell(for: tableView)
        TextFieldTableViewCell.registerCell(for: tableView)
    }

    fileprivate func showErrorAlert(_ errorMessage: String?) {
        let errorMessage = errorMessage ?? localized("error.socket.default_error_message")

        let alert = UIAlertController(
            title: localized("error.socket.default_error_title"),
            message: errorMessage,
            preferredStyle: .alert
        )
        alert.addAction(UIAlertAction(title: localized("global.ok"), style: .default, handler: nil))
        DispatchQueue.main.sync {
            self.present(alert, animated: true, completion: nil)
        }
    }

    @IBAction func buttonCreateDidPressed(_ sender: UIButton) {
        guard let roomName = setValues["room name"] as? String else { return }
        guard let publicRoom = setValues["public room"] as? Bool else { return }
        guard let readOnlyRoom = setValues["read only room"] as? Bool else { return }

        let roomType: RoomCreateType
        if publicRoom {
            roomType = .channel
        } else {
            roomType = .group
        }

        sender.isEnabled = false
        executeRequestCreateRoom(roomName: roomName, roomType: roomType, readOnlyRoom: readOnlyRoom) { [weak self] success, errorMessage in

            if success {
                self?.dismiss(animated: true, completion: nil)
            } else {
                self?.showErrorAlert(errorMessage)
                sender.isEnabled = true
            }
        }
    }

    fileprivate func executeRequestCreateRoom(roomName: String, roomType: RoomCreateType, readOnlyRoom: Bool, completion: @escaping (Bool, String?) -> Void) {
        API.shared.fetch(RoomCreateRequest(roomName: roomName, type: roomType, readOnly: readOnlyRoom)) { result in

            guard let success = result?.raw?["success"].boolValue,
                success == true else {
                    completion(false, result?.raw?["error"].string)
                    return
            }

            guard let auth = AuthManager.isAuthenticated() else { return }

            SubscriptionManager.updateSubscriptions(auth) { _ in
                if let newRoom = Realm.shared?.objects(Subscription.self).filter("name == '\(roomName)' && privateType != 'd'").first {

                    let controller = ChatViewController.shared
                    controller?.subscription = newRoom

                    completion(true, nil)
                } else {
                    completion(false, nil)
                }
            }
        }
    }

    @IBAction func buttonCloseDidPressed(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
}

// MARK: FormTableViewDelegate

extension NewRoomViewController: FormTableViewDelegate {
    func updateDictValue(key: String, value: Any) {
        setValues[key] = value

        if key == "public room",
            let value = value as? Bool,
            let cellRoomName = referenceOfCells["room name"] as? TextFieldTableViewCell {

            if value {
{'fraction_non_alphanumeric': 0.09838693517683599, 'fraction_numerical': 0.0024045686804929365, 'mean_word_length': 1.9637767220902613, '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': '808271', 'n_tokens_mistral': 2669, 'n_tokens_neox': 2495, 'n_words': 622}