import UIKit
import SDWebImage
import SwiftEventBus
import WowonderMessengerSDK
import Async
import Toast_Swift

class GroupVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var searchTextField: UITextField!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var emptyView: UIView!
    
    // MARK: - Properties
    
    private var fetchSatus = true
    private var groupChatRequestArray = [GroupRequestModel.GroupChatRequest]()
    private var groupsArray = [GroupData]()
    private var followingsArray = [UserData]()
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initialConfig()
    }
    
    deinit {
        SwiftEventBus.unregister(self)
    }
    
    // MARK: - Selectors
    
    // Back Button Action
    @IBAction func backButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.navigationController?.popViewController(animated: true)
    }
    
    // Qr Code Button Action
    @IBAction func qrCodeButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.dashboard.qrCodeVC() {
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // Create New Video Call Button Action
    @IBAction func createNewVideoCallButtonAction(_ sender: UIControl) {
        self.view.endEditing(true)
        AppInstance.instance.addCount =  AppInstance.instance.addCount! + 1
        if let newVC = R.storyboard.dashboard.selectContactVC() {
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // Create Group Chat Button Action
    @IBAction func createGroupButton(_ sender: UIControl) {
        self.view.endEditing(true)
        AppInstance.instance.addCount =  AppInstance.instance.addCount! + 1
        if let newVC = R.storyboard.group.createGroupViewController() {
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // Create Broadcast Button Action
    @IBAction func createBroadcastControlAction(_ sender: UIControl) {
        AppInstance.instance.addCount =  AppInstance.instance.addCount! + 1
        if let newVC = R.storyboard.broadcast.createBroadcastVC() {
            newVC.delegate = self
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // Chat With AI Chat Bot Button Action
    @IBAction func chatWithAIChatBotButtonAction(_ sender: UIButton) {
        AppInstance.instance.addCount =  AppInstance.instance.addCount! + 1
        if let newVC = R.storyboard.chat.chatGptVC() {
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.tableViewSetUp()
        self.textFieldSetup()
        self.fetchData()
        SwiftEventBus.onMainThread(self, name: EventBusConstants.EventBusConstantsUtils.EVENT_INTERNET_DIS_CONNECTED) { result in
            print("Internet dis connected!")
        }
    }
    
    // TableView Setup
    func tableViewSetUp() {
        self.tableView.dataSource = self
        self.tableView.delegate = self
        self.tableView.register( UINib(resource: R.nib.friendsTableItem), forCellReuseIdentifier: R.reuseIdentifier.friendsTableItem.identifier)
        self.tableView.refreshControl = UIRefreshControl()
        self.tableView.refreshControl?.addTarget(self, action: #selector(self.refresh), for: .valueChanged)
    }
    
    // TextField Setup
    func textFieldSetup() {
        self.searchTextField.attributedPlaceholder = NSAttributedString(
            string: "Search...",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.searchTextField.delegate = self
    }
    
    @objc func refresh() {
        self.fetchSatus = true
        self.followingsArray = []
        self.tableView.reloadData()
        self.fetchData()
    }
    
}

// MARK: - Extensions

// MARK: Api Call
extension GroupVC {
    
    private func fetchData() {
        self.showProgressDialog(text: NSLocalizedString("Loading...", comment: "Loading..."))
        if self.fetchSatus {
            self.fetchSatus = false
        } else {
            print("will not show Hud more...")
        }
        Async.background {
            FollowingManager.instance.getFollowings(user_id: AppInstance.instance.userId ?? "", session_Token: AppInstance.instance.sessionId ?? "") { (success, sessionError, serverError, error) in
                if success != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            self.followingsArray = success?.following ?? []
                            if self.followingsArray.count == 0 {
                                self.emptyView.isHidden = false
                                self.tableView.isHidden = true
                            } else {
                                self.emptyView.isHidden = true
                                self.tableView.isHidden = false
                            }
                            self.tableView.refreshControl?.endRefreshing()
                            self.tableView.reloadData()
                        }
                    }
                } else if sessionError != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            self.view.makeToast(sessionError?.errors?.error_text ?? "")
                        }
                    }
                } else if serverError != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            self.view.makeToast(serverError?.errors?.error_text ?? "")
                        }
                    }
                } else {
                    Async.main {
                        self.dismissProgressDialog {
                            self.view.makeToast(error?.localizedDescription ?? "")
                        }
                    }
                }
            }
        }
    }
    
    private func fetchData(textForSearch: String) {
        self.showProgressDialog(text: NSLocalizedString("Loading...", comment: "Loading..."))
        self.followingsArray.removeAll()
        self.tableView.reloadData()
        let sessionToken = AppInstance.instance.sessionId ?? ""
        Async.background {
            SearchManager.instance.searchForwardUser(session_Token: sessionToken, search_Key: textForSearch) { (success, sessionError, serverError, error) in
                if success != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            self.followingsArray = success?.users ?? []
                            if self.followingsArray.count == 0 {
                                self.tableView.isHidden = true
                                self.emptyView.isHidden = false
                            } else {
                                self.tableView.isHidden = false
                                self.emptyView.isHidden = true
                            }
                            self.tableView.reloadData()
                            self.tableView.refreshControl?.endRefreshing()
                        }
                    }
                } else if sessionError != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            self.view.makeToast(sessionError?.errors?.error_text ?? "")
                            print("sessionError = \(sessionError?.errors?.error_text ?? "")")
                        }
                    }
                } else if serverError != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            self.view.makeToast(serverError?.errors?.error_text)
                            print("serverError = \(serverError?.errors?.error_text ?? "")")
                        }
                    }
                } else {
                    Async.main {
                        self.dismissProgressDialog {
                            self.view.makeToast(error?.localizedDescription)
                            print("error = \(error?.localizedDescription ?? "")")
                        }
                    }
                }
            }
        }
    }
    
}

//MARK: - UITableViewDataSource & Delegate Method's

extension GroupVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.followingsArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.friendsTableItem.identifier) as! FriendsTableItem
        self.setGroupListData(cell: cell, indexPath: indexPath)
        return cell
    }
    
    func setGroupListData(cell: FriendsTableItem, indexPath: IndexPath) {
        let object = self.followingsArray[indexPath.row]
        cell.userNameLabel.text = object.name ?? ""
        cell.aboutLabel.text = "Last Seen " + (object.lastseen?.getLastSeenString(replace: false) ?? "")
        cell.verifiedImage.isHidden = object.is_verified == 0
        let imageUrl = URL.init(string: object.avatar ?? "")
        let indicator = SDWebImageActivityIndicator.medium
        cell.profileImage.sd_imageIndicator = indicator
        DispatchQueue.global(qos: .userInteractive).async {
            cell.profileImage.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: ""))
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let object = self.followingsArray[indexPath.row]
        if let newVC = R.storyboard.dashboard.userProfileViewController() {
            newVC.user_id =  object.user_id ?? ""
            newVC.user_data = object
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
}

// MARK: UITextFieldDelegate
extension GroupVC: UITextFieldDelegate {
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        let currentText = textField.text ?? ""
        if currentText != "" {
            self.fetchData(textForSearch: currentText)
        } else {
            self.fetchData()
        }
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        let currentText = textField.text ?? ""
        if currentText != "" {
            self.fetchData(textForSearch: currentText)
        } else {
            self.fetchData()
        }
    }
    
}

// MARK: CreateBroadcastVCDelegate
extension GroupVC: CreateBroadcastVCDelegate {
    
    func handleCreateBroadcast(broadcast: Broadcast?) {
        if let newVC = R.storyboard.broadcast.broadcastChatVC() {
            newVC.broadcast = broadcast
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
}
