
import UIKit
import Async
import WowonderMessengerSDK
import SDWebImage
import Toast_Swift

class SelectContactVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var tableView: UITableView!
    
    // MARK: - Properties
    
    private var selectContactArray: [UserData] = []
    let socketHelper = SocketHelper.shared
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        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.refreshControl = UIRefreshControl()
        self.tableView.refreshControl?.addTarget(self, action: #selector(self.refreshData), for: .valueChanged)
        self.tableView.register( UINib(resource: R.nib.contactCell), forCellReuseIdentifier: R.reuseIdentifier.contactCell.identifier)
    }
    
    @objc func refreshData() {
        self.fetchData()
    }
    
}

// MARK: - Extensions

// MARK: Api Call
extension SelectContactVC {
    
    private func fetchData() {
        self.selectContactArray = []
        self.tableView.reloadData()
        Async.background {
            SelectContactManger.instance.getContactList(user_id: AppInstance.instance.userId ?? "", session_Token: AppInstance.instance.sessionId ?? "",  list_type: "all") { (success, sessionError, serverError, error) in
                self.tableView.refreshControl?.endRefreshing()
                if success != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            print("userList = \(success?.users ?? [])")
                            self.selectContactArray = (success?.users)!
                            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 ?? "")")
                        }
                    }
                }
            }
        }
    }
    
    private func createAgoraCall(recipient_id: String, call_Type: String, user: UserData) {
        if Connectivity.isConnectedToNetwork() {
            Async.background {
                CallManager.instance.agoraCall(recipient_id: recipient_id, access_token: AppInstance.instance._sessionId, type: "create", call_Type: call_Type, completionBlock: { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.socketHelper.emit_user_notification(recipient_id: recipient_id)
                                switch call_Type {
                                case "audio":
                                    if let newVC = R.storyboard.call.agoraAudioCallVC() {
                                        newVC.outgoingCallData = success
                                        newVC.call_id = String(success?.id ?? 0)
                                        newVC.room_name = success?.room_name ?? ""
                                        newVC.userData = user
                                        self.navigationController?.pushViewController(newVC, animated: true)
                                    }
                                case "video":
                                    if let newVC = R.storyboard.call.agoraVideoCallVC() {
                                        newVC.outgoingCallData = success
                                        newVC.call_id = String(success?.id ?? 0)
                                        newVC.room_name = success?.room_name ?? ""
                                        newVC.userData = user
                                        self.navigationController?.pushViewController(newVC, animated: true)
                                    }
                                default:
                                    break
                                }
                            }
                        }
                    } 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)
            }
        }
    }
    
    private func createTwilioCall(recipient_id: String, call_Type: String, user: UserData) {
        if Connectivity.isConnectedToNetwork() {
            Async.background {
                TwilloCallmanager.instance.twilioCall(recipient_id: recipient_id, access_token: AppInstance.instance._sessionId, type: "create", call_Type: call_Type, completionBlock: { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.socketHelper.emit_user_notification(recipient_id: recipient_id)
                                switch call_Type {
                                case "audio":
                                    if let newVC = R.storyboard.call.twilioAudioCallVC() {
                                        newVC.outgoingCallData = success
                                        newVC.call_id = String(success?.id ?? 0)
                                        newVC.room_name = success?.room_name ?? ""
                                        newVC.userData = user
                                        self.navigationController?.pushViewController(newVC, animated: true)
                                    }
                                case "video":
                                    if let newVC = R.storyboard.call.twilioVideoCallVC() {
                                        newVC.outgoingCallData = success
                                        newVC.call_id = String(success?.id ?? 0)
                                        newVC.room_name = success?.room_name ?? ""
                                        newVC.userData = user
                                        self.navigationController?.pushViewController(newVC, animated: true)
                                    }
                                default:
                                    break
                                }
                            }
                        }
                    } 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: TableView Setup
extension SelectContactVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.selectContactArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.contactCell.identifier) as! ContactCell
        let object = self.selectContactArray[indexPath.row]
        cell.delegate = self
        cell.indexPath = indexPath
        cell.setData(object: object)
        return cell
    }
    
}

extension SelectContactVC: ContactCellDelegate {
    
    func handleCallButtonTap(indexPath: IndexPath, type: String) {
        let user = self.selectContactArray[indexPath.row]
        if AppInstance.instance.siteSetting?.agora_chat_video == "1" {
            self.createAgoraCall(recipient_id: user.user_id ?? "", call_Type: type, user: user)
        } else if AppInstance.instance.siteSetting?.twilio_video_chat == "1" {
            self.createTwilioCall(recipient_id: user.user_id ?? "", call_Type: type, user: user)
        }
    }
    
}
