import UIKit
import Async
import WowonderMessengerSDK
import Toast_Swift

class ManageSessionVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var tableView: UITableView!
    
    // MARK: - Properties
    
    var sessionArray = [SessionModel.Datum]()
    
    // 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.register( UINib(resource: R.nib.manageSessionTableItem), forCellReuseIdentifier: R.reuseIdentifier.manageSessionTableItem.identifier)
        self.tableView.refreshControl = UIRefreshControl()
        self.tableView.refreshControl?.addTarget(self, action: #selector(self.refreshData), for: .valueChanged)
    }
    
    @objc func refreshData() {
        self.fetchData()
    }
    
}

// MARK: - Extensions

// MARK: Api Call
extension ManageSessionVC {
    
    private func fetchData() {
        if Connectivity.isConnectedToNetwork() {
            self.sessionArray = []
            self.tableView.reloadData()
            let sessionToken = AppInstance.instance.sessionId ?? ""
            Async.background {
                SessionManager.instance.getSession(session_Token: sessionToken, type: "get") { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.sessionArray = success?.data ?? []
                                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 deleteSession(id: String, index: Int) {
        if Connectivity.isConnectedToNetwork() {
            let sessionToken = AppInstance.instance.sessionId ?? ""
            Async.background {
                SessionManager.instance.deleteSession(session_Token: sessionToken, type: "delete", id: id) { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main({
                            self.dismissProgressDialog {
                                self.sessionArray.remove(at: index)
                                self.tableView.reloadData()
                            }
                        })
                    } 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)
            }
        }
    }
    
}

// MARK: TableView Setup
extension ManageSessionVC: UITableViewDataSource, UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.sessionArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier:R.reuseIdentifier.manageSessionTableItem.identifier) as! ManageSessionTableItem
        cell.delegate = self
        cell.deleteButton.tag = indexPath.row
        let object = self.sessionArray[indexPath.row]
        cell.bind(object)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        AppInstance.instance.addCount = AppInstance.instance.addCount! + 1
    }
    
}

// MARK: ManageSessionTableItemDelegate Methods
extension ManageSessionVC: ManageSessionTableItemDelegate {
    
    func handleDeleteButtonTap(_ sender: UIButton) {
        if let alertVC = R.storyboard.popup.warningAlertVC() {
            alertVC.delegate = self
            alertVC.titleText  = "Warning !"
            alertVC.messageText = "Are you sure you went to log out from this device?"
            self.present(alertVC, animated: true, completion: nil)
            alertVC.okButton.tag = sender.tag
        }
    }
    
}

// MARK: -=
extension ManageSessionVC: WarningAlertVCDelegate {
    
    func chatAlertOKButtonPressed(_ sender: UIButton) {
        let id = self.sessionArray[sender.tag].id ?? ""
        self.deleteSession(id: id, index: sender.tag)
    }
    
}
