
import UIKit
import SwiftEventBus
import WowonderMessengerSDK
import SDWebImage
import Async
import Toast_Swift
import DropDown

class CallHistoryVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var searchButton: UIButton!
    @IBOutlet weak var moreButton: UIButton!
    @IBOutlet weak var findFriendButton: UIButton!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var emptyView: UIView!
    
    // MARK: - Properties
    
    let socketHelper = SocketHelper.shared
    private var callLogs: [CallLogModel] = []
    var userData: UserData?
    private let dropDown = DropDown()
    private var dropDownDataSource = [
        "Request",
        "Broadcast"
    ]
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initialConfig()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.getCallLogs()
        SwiftEventBus.postToMainThread("settings", sender: 2)
    }
    
    // MARK: - Selectors
    
    // Seacrh Button Action
    @IBAction func searchButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.dashboard.searchRandomVC() {
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // More Button Action
    @IBAction func moreButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.dropDown.show()
    }
    
    // Find Friend Button Action
    @IBAction func findFriendButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.dashboard.findFriendsViewController() {
            newVC.findFriendFilterModel.distance = "1"
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.setupDropDown()
        self.tableViewSetup()
    }
    
    // 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.callLogCell), forCellReuseIdentifier: R.reuseIdentifier.callLogCell.identifier)
    }
    
    private func setupDropDown() {
        self.dropDown.dataSource = self.dropDownDataSource
        self.dropDown.anchorView = self.moreButton
        self.dropDown.width = 160
        self.dropDown.bottomOffset = CGPoint(x: -124, y: 34)
        self.dropDown.direction = .bottom
        self.dropDown.sizeToFit()
        self.dropDown.selectionAction = { [unowned self] (index: Int, item: String) in
            if item == "Request" {
                if let newVC = R.storyboard.dashboard.requestViewController() {
                    self.navigationController?.pushViewController(newVC, animated: true)
                }
            }
            if item == "Broadcast" {
                if let newVC = R.storyboard.broadcast.broadcastVC() {
                    self.navigationController?.pushViewController(newVC, animated: true)
                }
            }
            self.dropDown.deselectRow(at: index)
            self.view.endEditing(true)
            self.dropDown.hide()
        }
    }
    
    @objc func refreshData() {
        self.getCallLogs()
    }
    
    func getCallLogs() {
        self.callLogs = []
        let allData =  UserDefaults.standard.getCallLogs(Key: Local.CALL_LOGS.CallLogs)
        allData.forEach { data in
            let callLog = try? PropertyListDecoder().decode(CallLogModel.self ,from: data)
            if let callLog = callLog {
                self.callLogs.append(callLog)
            }
        }
        self.callLogs.reverse()
        self.tableView.reloadData()
        self.tableView.refreshControl?.endRefreshing()
    }
    
}

// MARK: - Extensions

// MARK: Api Call
extension CallHistoryVC {
    
    private func fetchUserProfile(user_id: String, call_Type: String) {
        let status = AppInstance.instance.getUserSession()
        if status {
            let sessionId = AppInstance.instance._sessionId
            Async.background {
                GetUserDataManager.instance.getUserData(user_id: user_id, session_Token: sessionId, fetch_type: API.Params.user_data) { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.userData = success?.user_data
                            if AppInstance.instance.siteSetting?.agora_chat_video == "1" {
                                self.createAgoraCall(recipient_id: self.userData?.user_id ?? "", call_Type: call_Type, user: self.userData)
                            } else if AppInstance.instance.siteSetting?.twilio_video_chat == "1" {
                                self.createTwilioCall(recipient_id: self.userData?.user_id ?? "", call_Type: call_Type, user: self.userData)
                            }
                        }
                    } else if sessionError != nil {
                        Async.main {
                            self.view.makeToast(sessionError?.errors?.error_text)
                        }
                    } else if serverError != nil {
                        Async.main {
                            self.view.makeToast(serverError?.errors?.error_text)
                        }
                    } else {
                        Async.main {
                            self.view.makeToast(error?.localizedDescription)
                        }
                    }
                }
            }
        } else {
            print(InterNetError)
        }
    }
    
    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 CallHistoryVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.callLogs.count == 0 {
            self.emptyView.isHidden = false
            self.tableView.backgroundView = self.emptyView
        } else {
            self.emptyView.isHidden = true
            self.tableView.backgroundView = nil
        }
        return self.callLogs.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.callLogCell.identifier) as! CallLogCell
        let object = self.callLogs[indexPath.row]
        cell.delegate = self
        cell.indexPath = indexPath
        cell.setData(object: object)
        return cell
    }
    
}

extension CallHistoryVC: CallLogCellDelegate {
    
    func handleCallButtonTap(indexPath: IndexPath) {
        let callLog = self.callLogs[indexPath.row]
        if let newVC = R.storyboard.popup.callAlertVC() {
            newVC.delegate = self
            newVC.callLog = callLog
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            self.present(newVC, animated: true)
        }
    }
    
}

extension CallHistoryVC: CallAlertVCDelegate {
    
    func handleCallAlertOptionTap(callLog: CallLogModel, call_Type: String) {
        self.fetchUserProfile(user_id: callLog.user_id ?? "", call_Type: call_Type)
    }
    
}

