import UIKit
import Async
import WowonderMessengerSDK
import Toast_Swift
import SwiftEventBus

class GetFriendVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var headerLabel: UILabel!
    @IBOutlet weak var backButton: UIButton!
    @IBOutlet weak var searchTextField: UITextField!
    @IBOutlet weak var searchButton: UIButton!
    @IBOutlet weak var searchClearButton: UIButton!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var emptyView: UIView!
    
    // MARK: - Properties
    
    private var followingsArray: [UserData] = []
    private var refreshControl = UIRefreshControl()
    var isSearch = false
    var message: Messages?
    var userData: UserData?
    var isGroupMessage = false
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initialConfig()
    }
    
    // MARK: - Selectors
    
    // Back Button Action
    @IBAction func backButtonAction(_ sender: UIButton) {
        if self.isSearch {
            self.isSearch = false
            self.searchButton.isHidden = false
            self.headerLabel.isHidden = false
            self.searchTextField.text = ""
            self.searchTextField.resignFirstResponder()
            self.searchTextField.isHidden = true
            self.searchClearButton.isHidden = true
        } else {
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    // Search Button Action
    @IBAction func searchButtonAction(_ sender: UIButton) {
        self.isSearch = true
        self.searchButton.isHidden = true
        self.headerLabel.isHidden = true
        self.searchTextField.isHidden = false
        self.searchTextField.becomeFirstResponder()
    }
    
    // Search Clear Button Action
    @IBAction func searchClearButtonAction(_ sender: UIButton) {
        self.searchTextField.text = ""
        self.searchClearButton.isHidden = true
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.tableViewSetup()
        self.textFieldSetup()
        self.fetchData()
    }
    
    // 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.refreshControl.attributedTitle = NSAttributedString(string: "")
        self.refreshControl.addTarget(self, action: #selector(self.refresh(sender:)), for: UIControl.Event.valueChanged)
        self.tableView.addSubview(refreshControl)
    }
    
    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(sender: AnyObject) {
        self.fetchData()
    }
    
    private func fetchData() {
        self.followingsArray.removeAll()
        self.tableView.reloadData()
        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.tableView.isHidden = true
                                self.emptyView.isHidden = false
                            } else {
                                self.tableView.isHidden = false
                                self.emptyView.isHidden = true
                            }
                            self.tableView.reloadData()
                            self.refreshControl.endRefreshing()
                        }
                    })
                } 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.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.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 ?? "")")
                        }
                    }
                }
            }
        }
    }
    
    // React Message Api Call
    private func forwardMessageApi(message_id: String, recipient_id: String) {
        Async.background {
            ChatManager.instance.forwardMessage(message_id: message_id, recipient_id: recipient_id, completionBlock: { (success, sessionError, serverError, error) in
                if success != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            print(success?.message_data as Any)
                            if !self.isGroupMessage {
                                if (self.userData?.user_id ?? "") == recipient_id {
                                    self.navigationController?.popViewController(animated: true)
                                } else {
                                    self.navigationController?.popToRootViewController(animated: true)
                                    SwiftEventBus.post("ForwardMessage", sender: recipient_id)
                                }
                            } else {
                                self.navigationController?.popViewController(animated: true)
                            }
                        }
                    }
                } 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)
                        }
                    }
                }
            })
        }
    }
    
}

// MARK: - Extensions

// MARK: TableView Setup
extension GetFriendVC: UITableViewDataSource, UITableViewDelegate {
    
    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
        let object = followingsArray[indexPath.row]
        cell.setData(object: object)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.forwardMessageApi(message_id: self.message?.message_id ?? "", recipient_id: self.followingsArray[indexPath.row].user_id ?? "")
    }
    
}

// MARK: UITextFieldDelegate
extension GetFriendVC: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let currentText = textField.text ?? ""
        let updatedText = (currentText as NSString).replacingCharacters(in: range, with: string)
        if updatedText.count == 0 {
            self.searchClearButton.isHidden = true
        } else {
            self.searchClearButton.isHidden = false
        }
        return true
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        let currentText = textField.text ?? ""
        if currentText != "" {
            self.fetchData(textForSearch: currentText)
        }
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        let currentText = textField.text ?? ""
        if currentText != "" {
            self.fetchData(textForSearch: currentText)
        }
    }
    
}
