import UIKit
import Async
import WowonderMessengerSDK
import SDWebImage

class FollowingVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var headerLabel: UILabel!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var emptyView: UIView!
    
    // MARK: - Properties
    
    var user_id = ""
    var type = ""
    private var userArray: [UserData] = []
    private var refreshControl = UIRefreshControl()
    private let color = UIColor.accent
    
    // 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()
        switch self.type {
        case "Following":
            self.headerLabel.text = "Following"
            self.getFollowings()
        case "Followers":
            self.headerLabel.text = "Followers"
            self.getFollowers()
        default:
            break
        }
    }
    
    // TableView Setup
    func tableViewSetup() {
        self.tableView.dataSource = self
        self.tableView.delegate = self
        self.tableView.register( UINib(resource: R.nib.searchRandomTableCell), forCellReuseIdentifier: R.reuseIdentifier.searchRandomTableCell.identifier)
        self.refreshControl.attributedTitle = NSAttributedString(string: "")
        self.refreshControl.addTarget(self, action: #selector(self.refresh(sender:)), for: UIControl.Event.valueChanged)
        self.tableView.addSubview(refreshControl)
    }
    
    @objc func refresh(sender: AnyObject) {
        switch self.type {
        case "Following":
            self.getFollowings()
        case "Followers":
            self.getFollowers()
        default:
            break
        }
    }
    
    private func getFollowings() {
        self.userArray.removeAll()
        self.tableView.reloadData()
        self.showProgressDialog(text: NSLocalizedString("Loading...", comment: "Loading..."))
        Async.background {
            FollowingManager.instance.getFollowings(user_id: self.user_id, session_Token: AppInstance.instance.sessionId ?? "") { (success, sessionError, serverError, error) in
                if success != nil {
                    Async.main({
                        self.dismissProgressDialog {
                            self.userArray = success?.following ?? []
                            if self.userArray.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 ?? "")")
                        }
                    }
                }
            }
        }
    }
    
    private func getFollowers() {
        self.userArray.removeAll()
        self.tableView.reloadData()
        self.showProgressDialog(text: NSLocalizedString("Loading...", comment: "Loading..."))
        Async.background {
            FollowingManager.instance.getFollowers(user_id: self.user_id, session_Token: AppInstance.instance.sessionId ?? "") { (success, sessionError, serverError, error) in
                if success != nil {
                    Async.main({
                        self.dismissProgressDialog {
                            self.userArray = success?.followers ?? []
                            if self.userArray.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 ?? "")")
                        }
                    }
                }
            }
        }
    }
    
}

// MARK: - Extensions

// MARK: TableView Setup
extension FollowingVC: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.userArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.searchRandomTableCell.identifier) as! SearchRandomTableCell
        self.setDataUser(cell: cell, indexPath: indexPath)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let object = userArray[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)
        }
    }
    
    func setDataUser(cell: SearchRandomTableCell, indexPath: IndexPath) {
        let obj = self.userArray[indexPath.row]
        let url = URL(string: obj.avatar ?? "")
        cell.delegate = self
        cell.indexPath = indexPath
        let indicator = SDWebImageActivityIndicator.medium
        cell.profileImage.sd_imageIndicator = indicator
        DispatchQueue.global(qos: .userInteractive).async {
            cell.profileImage.sd_setImage(with: url, placeholderImage: UIImage(named: ""))
        }
        cell.userNameLabel.text = obj.name
        cell.verifiedImage.isHidden = obj.is_verified == 0
        cell.aboutLabel.text = obj.lastseen?.getLastSeenString(replace: false)
        /*if obj.lastseen_status == "on"{
         cell.statusImageView.image = R.image.icon_online_vector()
         } else {
         cell.statusImageView.image = R.image.icon_offline_vector()
         }*/
        if obj.can_follow == 0 && obj.is_following == 0 && obj.user_id != AppInstance.instance.userProfile?.user_id {
            cell.followButton.isHidden = true
        }
        if obj.follow_privacy == "0" {
            cell.followButton.isHidden = false
        } else if obj.follow_privacy == "1" {
            if (obj.is_following_me == 0) {
                cell.followButton.isHidden = obj.is_following == 0 ? true : false
            } else if (obj.is_following_me == 1) {
                cell.followButton.isHidden = false
            }
        } else {
            cell.followButton.isHidden = false
        }
        if obj.is_following == 1 {
            cell.followButton.backgroundColor = .accent
            cell.followButton.setTitleColor(.gnt_white, for: .normal)
            cell.followButton.setTitle("Following", for: .normal)
        } else {
            cell.followButton.backgroundColor = .clear
            cell.followButton.borderColorV = .accent
            cell.followButton.borderWidthV = 1
            cell.followButton.setTitleColor(.accent, for: .normal)
            cell.followButton.setTitle("Follow", for: .normal)
        }
    }
    
}

// MARK: SearchRandomTableCellDelegate
extension FollowingVC: SearchRandomTableCellDelegate {
    
    func handleFollowButtonTap(_ sender: UIButton, indexPath: IndexPath) {
        if userArray.count > indexPath.row {
            let user = self.userArray[indexPath.row]
            if user.is_following == 1 {
                if let messageAlertVC = R.storyboard.popup.messageAlertVC() {
                    messageAlertVC.delegate = self
                    messageAlertVC.messageText = "Are you sure you want to remove this user as your friend?"
                    self.present(messageAlertVC, animated: true, completion: nil)
                    messageAlertVC.confirmButton.tag = indexPath.row
                }
            } else {
                self.followUser(indexPath: indexPath)
            }
        }
    }
    func followUser(indexPath: IndexPath) {
        let user = self.userArray[indexPath.row]
        if Connectivity.isConnectedToNetwork() {
            Async.background {
                FollowingManager.instance.followRequest(user_Id: user.user_id ?? "",  ServerKey: AppInstance.instance._sessionId) { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                print("userList = \(success?.follow_status ?? "")")
                                self.view.makeToast(success?.follow_status ?? "")
                                if success?.follow_status ?? "" == "followed" {
                                    self.userArray[indexPath.row].is_following = 1
                                } else {
                                    self.userArray[indexPath.row].is_following = 0
                                }
                                self.tableView.reloadRows(at: [indexPath], with: .automatic)
                            }
                        }
                    } 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)
                            }
                        }
                    }
                }
            }
        } else {
            self.dismissProgressDialog {
                self.view.makeToast(InterNetError)
            }
        }
    }
    
}

// MARK: MessageAlertVCDelegate Methods
extension FollowingVC: MessageAlertVCDelegate {
    
    func messageAlertConfirmButtonPressed(_ sender: UIButton) {
        self.followUser(indexPath: IndexPath(item: sender.tag, section: 0))
    }
    
}
