import UIKit
import Async
import WowonderMessengerSDK
import Toast_Swift
import SDWebImage

class BlockedUsersVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var emptyView: UIView!
    
    // MARK: - Properties
    
    private var blockedUsersArray: [UserData] = []
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initialConfig()
    }
    
    // MARK: - Selectors
    
    // Back Button Action
    @IBAction func backButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.navigationController?.popViewController(animated: true)
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.tableViewSetup()
        self.fetchData()
    }
    
    // TableView Setup
    func tableViewSetup() {
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.separatorStyle = .none
        self.tableView.refreshControl = UIRefreshControl()
        self.tableView.refreshControl?.addTarget(self, action: #selector(self.refreshData), for: .valueChanged)
        self.tableView.register( UINib(resource: R.nib.blockedUsersTableCell), forCellReuseIdentifier: R.reuseIdentifier.blockedUsersTableCell.identifier)
    }
    
    @objc func refreshData() {
        self.blockedUsersArray = []
        self.tableView.reloadData()
        self.fetchData()
    }
    
}

// MARK: - Extensions

// MARK: Api Call
extension BlockedUsersVC {
    
    private func fetchData() {
        if Connectivity.isConnectedToNetwork() {
            self.blockedUsersArray = []
            let sessionToken = AppInstance.instance.sessionId ?? ""
            self.showProgressDialog(text: NSLocalizedString("Loading...", comment: "Loading..."))
            Async.background {
                BlockUsersManager.instance.getBlockedUsers(session_Token: sessionToken, completionBlock: { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                print("userList = \(success?.blockedUsers ?? [])")
                                self.blockedUsersArray = success?.blockedUsers ?? []
                                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 ?? "")")
                            }
                        }
                    }
                })
            }
        } else {
            self.dismissProgressDialog {
                self.view.makeToast(InterNetError)
            }
        }
    }
    
    private func blockUser(user_id: String, userName: String, indexPath: Int) {
        if Connectivity.isConnectedToNetwork() {
            Async.background {
                BlockUsersManager.instance.blockUser(user_id: user_id, block_action: "un-block", completionBlock: { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.blockedUsersArray.remove(at: indexPath)
                                self.tableView.reloadData()
                                print("userList = \(success?.blockStatus ?? "")")
                                self.view.makeToast("\(userName) has been unblocked!!")
                            }
                        }
                    } 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 ?? "")")
                            }
                        }
                    }
                })
            }
        } else {
            self.view.makeToast(InterNetError)
        }
    }
}

// MARK: TableView Setup
extension BlockedUsersVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.blockedUsersArray.count == 0 {
            self.tableView.backgroundView = self.emptyView
        } else {
            self.tableView.backgroundView = nil
        }
        return self.blockedUsersArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.blockedUsersTableCell.identifier) as! BlockedUsersTableCell
        self.setBlockedUserData(cell: cell, indexPath: indexPath)
        return cell
    }
    
    func setBlockedUserData(cell: BlockedUsersTableCell, indexPath: IndexPath) {
        let object = blockedUsersArray[indexPath.row]
        cell.delegate = self
        cell.unblockButton.tag = indexPath.row
        cell.usernameLabel.text = object.name ?? ""
        cell.lastSeenLabel.text = "Last Seen " + (object.lastseen?.getLastSeenString(replace: false) ?? "")
        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: ""))
        }
    }
    
}

// MARK: BlockedUsersTableCellDelegate Methods
extension BlockedUsersVC: BlockedUsersTableCellDelegate {
    
    func handleUnblockButtonTap(_ sender: UIButton) {
        let object = blockedUsersArray[sender.tag]
        self.blockUser(user_id: object.user_id ?? "", userName: object.username ?? "", indexPath: sender.tag)
    }
    
}
