//
//  ChatViewController.swift
//  Em-call
//
//  Created by Alex Sh on 15.02.2022.
//

import UIKit

class ChatViewController: UIViewController {
    /*
     "wetywet wywy ywywy w tyhy jdjd kufkfyklfyilf urstesa gesg esh sehsh",
     "ghyeyrh ery  etjirtijeti  etj retuje  rukryu rujr  etyuetyet  etyjtj",
     "erhehet yhey thyhheheh",
     "jkyujtueje  ewrh  ewje jet etjetyerhwrh erherh ehrhh rhrwh ewrh wh w",
     "rshtrh rh  srh ss hsr rhethrtsh srtghr r ryesty rtyr errysrtewreyu eju",
     "drh rrhys srhsr srhsrh srtyrs srtysrtysrty srty srtysry rs",
     "nh;sorkh erkltja a,ewrtlwrt vs,fnwlrwel;rjlmv LDSFoawhrpgry pipypkrae"
     */
    let tableView = UITableView()
    let messageInputBar = MessageInputView()
    let chatRoom = ChatRoom()
    
    var messages: [Message] = []
    
    var username = "Alex"
    var flagStartChat = 0
    //debug
    let SERVER_NO = 1
    /*
    override func viewDidLoad() {
        super.viewDidLoad()
        self.hideKeyboardWhenTappedAround()
    }*/
                      
    @objc func call_Method () {
    print("Click")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.setNavigationBarHidden(false, animated: animated)
        self.navigationController?.navigationBar.titleTextAttributes = [.foregroundColor : UIColor.black]
        self.navigationController?.navigationBar.barTintColor = UIColor.white
        self.navigationController?.navigationBar.topItem?.title = "CHAT"
        self.navigationController?.navigationItem.title = "CHAT"
        
        chatRoom.delegate = self
 
    }
    override func viewWillDisappear(_ animated: Bool) {
      super.viewWillDisappear(animated)
        if flagStartChat == 1 {
      chatRoom.stopChatSession()
            flagStartChat = 0
        }
        
    }
    
    @IBAction func startChat(_ sender: Any) {
        flagStartChat = 1
        loadViews()
        if SERVER_NO == 0 {
        chatRoom.setupNetworkCommunication()
         chatRoom.joinChat(username: username)
        }
    }
    
}

// Put this piece of code anywhere you like
extension UIViewController {
    //Now in every UIViewController, all you have to do is call this function:
    func hideKeyboardWhenTappedAround() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
        tap.cancelsTouchesInView = false
        view.addGestureRecognizer(tap)
    }
    
    @objc func dismissKeyboard() {
        view.endEditing(true)
    }
}
//MARK - Message Input Bar
extension ChatViewController: MessageInputDelegate {
  func sendWasTapped(message: String) {
    chatRoom.send(message: message)
  }
}

extension ChatViewController: ChatRoomDelegate {
  func received(message: Message) {
    insertNewMessageCell(message)
  }
}

