//
//  AddFriendViewModel.swift


import Foundation
import Contacts
import UIKit
import SSSpinnerButton

class AddFriendViewModel : NSObject{
    
    var userDefaultManager : UserDefaultManager = UserDefaultManager.shared
    
    var pendingFriendReqData : BoxBind<[PendingFriendReqListModel]> = BoxBind([PendingFriendReqListModel]())
    var arrFriendReqData : BoxBind<[ReceivedReqListModel]> = BoxBind([ReceivedReqListModel]())
    var arrFriendListData : BoxBind<[FriendListModel]> = BoxBind([FriendListModel]())
    
    override init() {
        super.init()
        self.callFriendReqAPI()
        self.callPendingFriendReqAPI()
        self.callFriendListAPI()
    }
    
    //MARK: - Add friend API
    func callAddFriendAPI(phonoNo: String, countryCode: String, completion : @escaping(Bool) -> ()){
        APIDataManager.shared.callSendFriendRequestAPI(phonoNo: phonoNo, countryCode: countryCode) { (success) in
            if success{
                completion(success)
            }
            else{
                completion(success)
            }
        }
    }
    
    //MARK: - Pending friend list API
    func callPendingFriendReqAPI(){
        APIDataManager.shared.getPendingFriendRequest { success in
            self.pendingFriendReqData.value = success
        } failure: { (error) in
            debugPrint("Error Occured",error)
            self.pendingFriendReqData.value = []
        }
    }
    
    //MARK: - Friend Req List API
    func callFriendReqAPI(){
        APIDataManager.shared.getFriendRequest { success in
            self.arrFriendReqData.value = success
        } failure: { (error) in
            debugPrint("Error Occured",error)
            self.arrFriendReqData.value = []
        }
    }
    
    //MARK: - Friend List API
    func callFriendListAPI(){
        APIDataManager.shared.getFriendListAPI { success in
            self.arrFriendListData.value = success
        } failure: { (error) in
            debugPrint("Error Occured",error)
            self.arrFriendListData.value = []
        }
    }
    
    //MARK: - Remove Friend Alert
    func showActionSheet(index : Int){
        let dataId = self.arrFriendListData.value[index].friend_id
        let actionSheet = UIAlertController(title: "Remove \(self.arrFriendListData.value[index].full_name ?? "") from\nyour \(APP_NAME)?", message: Alert_Message.removeAlertMsg, preferredStyle: .alert)

        let removeAction = UIAlertAction(title: Alert_Message.Remove, style: .destructive) { (action) in
            if Reachability.isInternetAvailable{
                if self.arrFriendListData.value.count != 0{
                    if self.arrFriendListData.value[index].friend_id == dataId{
                        APIDataManager.shared.unfriendAPI(friendId: self.arrFriendListData.value[index].friend_id ?? 0) { success,message  in
                            debugPrint(success)
                            if success{
                                if let index = self.arrFriendListData.value.firstIndex(where: { $0.friend_id == self.arrFriendListData.value[index].friend_id }){
                                    self.arrFriendListData.value.remove(at: index)
                                }
                            }
                            else{
                                Utilities.showAlertView(nil, message) { _ in}
                            }
                        }
                    }
                }
            }
            else{
                Utilities.showAlertView(nil, Alert_Message.networkAlertMsg) { _ in}
            }
        }

        let cancelAction = UIAlertAction(title: Alert_Message.Cancel, style: .cancel) { (action) in
            debugPrint("didPress cancel")
        }
        
        actionSheet.addAction(cancelAction)
        actionSheet.addAction(removeAction)

        if let currentVC = UIApplication.shared.topViewController() as? AddFriendViewController {
            currentVC.present(actionSheet, animated: true, completion: nil)
        }
    }
    
    //MARK: - Unfriend API
    @objc func callUnfriendAPI(sender: UIButton){
        self.showActionSheet(index: sender.tag)
    }
    
    //MARK: - Remove Pending Req Alert
    func showRemoveReqAlert(index : Int){
        let dataId = self.pendingFriendReqData.value[index].request_id
        let actionSheet = UIAlertController(title: "Remove friend request?", message: "If you remove your friend request to \(self.pendingFriendReqData.value[index].receiver_name ?? ""), you can always add them again later.", preferredStyle: .alert)

        let removeAction = UIAlertAction(title: Alert_Message.Remove, style: .destructive) { (action) in
            if Reachability.isInternetAvailable{
                if self.pendingFriendReqData.value.count != 0{
                    if self.pendingFriendReqData.value[index].request_id == dataId{
                        APIDataManager.shared.canclePendingRequest(requestId: self.pendingFriendReqData.value[index].request_id ?? 0) { success,message in
                            if success{
                                if self.pendingFriendReqData.value.count != 0{
                                    self.pendingFriendReqData.value.remove(at: index)
                                }
                            }
                            else{
                                Utilities.showAlertView(nil, message) { _ in}
                            }
                        }
                    }
                }
            }
            else{
                Utilities.showAlertView(nil, Alert_Message.networkAlertMsg) { _ in}
            }
        }

        let cancelAction = UIAlertAction(title: Alert_Message.Cancel, style: .cancel) { (action) in
            debugPrint("didPress cancel")
        }
        
        actionSheet.addAction(cancelAction)
        actionSheet.addAction(removeAction)

        if let currentVC = UIApplication.shared.topViewController() as? AddFriendViewController {
            currentVC.present(actionSheet, animated: true, completion: nil)
        }
    }
    
    //MARK: - Accept and Reject API
    @objc func callAcceptReqAPI(_ sender: UITapGestureRecognizer) {
        if let sender = sender as? CustomTapGesture {
            sender.addBtn.startAnimate(spinnerType: .ballRotateChase, spinnercolor: .black, spinnerSize: 15, complete: nil)
            
            if sender.section == 0{
                if Reachability.isInternetAvailable{
                    if self.arrFriendReqData.value.count != 0{
                        APIDataManager.shared.callAcceptAndRejectReqAPI(requestId: self.arrFriendReqData.value[sender.index].request_id ?? 0, status: "accept", completion: { success,message in
                            sender.addBtn.stopAnimate {
                                if success{
                                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
                                        if let index = self.arrFriendReqData.value.firstIndex(where: { $0.request_id ==
                                            self.arrFriendReqData.value[sender.index].request_id }){
                                            self.arrFriendReqData.value.remove(at: index)
                                        }
//                                        if FIRRemoteManagement.shared.isShow_NativeReviewPopup{
//                                            ScreenManager.shared.showNativeReviewPopup()
//                                        }
                                    })
                                    
                                }
                                else{
                                    Utilities.showAlertView(nil, message) { _ in}
                                }
                            }
                        })
                    }
                }
                else{
                    Utilities.showAlertView(nil, Alert_Message.networkAlertMsg) { value in
                        sender.addBtn.stopAnimate(complete: nil)
                    }
                }
            }
            else{
                //Resend Request
                if Reachability.isInternetAvailable{
                    if self.pendingFriendReqData.value.count != 0{
                        self.callAddFriendAPI(phonoNo: self.pendingFriendReqData.value[sender.index].phone ?? "", countryCode: self.pendingFriendReqData.value[sender.index].country_code ?? "") { (success) in
                            debugPrint(success)
                            sender.addBtn.stopAnimate(complete: nil)
                        }
                    }
                }
                else{
                    Utilities.showAlertView(nil, Alert_Message.networkAlertMsg) { value in
                        sender.addBtn.stopAnimate(complete: nil)
                    }
                }
            }
        }
    }
    
    
    @objc func callRejectReqAPI(_ sender: UITapGestureRecognizer) {
        if let sender = sender as? CustomTapGesture {
            if Reachability.isInternetAvailable{
                if sender.section == 0{
                    self.showRejectReqAlert(index: sender.index)
//                    if self.arrFriendReqData.value.count != 0 {
//                        APIDataManager.shared.callAcceptAndRejectReqAPI(requestId: self.arrFriendReqData.value[sender.index].request_id ?? 0, status: "reject", completion: { _ in
//                            self.arrFriendReqData.value.remove(at: sender.index)
//                        })
//                    }
                }
                else{
                    self.showRemoveReqAlert(index: sender.index)
                }
            }
            else{
                Utilities.showAlertView(nil, Alert_Message.networkAlertMsg) { _ in}
            }
        }
    }
    
    //MARK: - Reject Req Alert
    func showRejectReqAlert(index : Int){
        let dataId = self.arrFriendReqData.value[index].request_id
        let actionSheet = UIAlertController(title: "Reject friend request?", message: "Are you sure you want to reject friend request?", preferredStyle: .alert)

        let removeAction = UIAlertAction(title: Alert_Message.Remove, style: .destructive) { (action) in
            if Reachability.isInternetAvailable{
                if self.arrFriendReqData.value.count != 0 {
                    if self.arrFriendReqData.value[index].request_id == dataId{
                        APIDataManager.shared.callAcceptAndRejectReqAPI(requestId: self.arrFriendReqData.value[index].request_id ?? 0, status: "reject", completion: { success,message in
                            if success{
                                self.arrFriendReqData.value.remove(at: index)
                            }
                            else{
                                Utilities.showAlertView(nil, message) { _ in}
                            }
                        })
                    }
                }
            }
            else{
                Utilities.showAlertView(nil, Alert_Message.networkAlertMsg) { _ in}
            }
        }

        let cancelAction = UIAlertAction(title: Alert_Message.Cancel, style: .cancel) { (action) in
            debugPrint("didPress cancel")
        }
        
        actionSheet.addAction(cancelAction)
        actionSheet.addAction(removeAction)

        if let currentVC = UIApplication.shared.topViewController() as? AddFriendViewController {
            currentVC.present(actionSheet, animated: true, completion: nil)
        }
    }
    
    
    //MARK: - Datasource & Delegate0
    
    func getCellCountForDisplay(selectedSegment : Int, section : Int) -> Int{
        switch selectedSegment{
        case 0 :
            return self.arrFriendListData.value.count
        case 1 :
            if section == 0{
                return self.arrFriendReqData.value.count
            }
            else{
                return self.pendingFriendReqData.value.count
            }
            
        default:
            return 0
        }
    }
    
    func perpareCellForDisplay(tableView: UITableView, indexPath: IndexPath, friendList : [FriendListModel], friendReqData : [ReceivedReqListModel], pendingReqData : [PendingFriendReqListModel],selectedSegment : Int) -> UITableViewCell{
        switch selectedSegment{
            
        case 0 :
            
            let cell = tableView.dequeueReusableCell(withIdentifier: FriendListTVCell.identifier, for: indexPath) as! FriendListTVCell
            cell.btnRemoveFriend.tag = indexPath.row

            cell.lblFriendName.text = friendList[indexPath.row].full_name ?? ""
            if friendList[indexPath.row].full_name != ""{
                cell.lblPrefixFriend.text = friendList[indexPath.row].full_name?[0]
            }
            cell.btnRemoveFriend.addTarget(self, action: #selector(callUnfriendAPI(sender:)), for: .touchUpInside)
            return cell
            
        case 1 :
            
            let cell = tableView.dequeueReusableCell(withIdentifier: SuggestionTVCell.identifier, for: indexPath) as! SuggestionTVCell
            cell.btnAccept.tag = (indexPath.section * 1000) + indexPath.row
            cell.btnReject.tag = (indexPath.section * 1000) + indexPath.row
            cell.btnReject.layer.cornerRadius = cell.btnRejectHeight.constant / 2
            if indexPath.section == 0 {
                cell.friendName.text = friendReqData[indexPath.row].sender_name
                if friendReqData[indexPath.row].sender_name != ""{
                    cell.friendNamePrefix.text = friendReqData[indexPath.row].sender_name?[0]
                }
                cell.btnAccept.setTitle("Accept", for: .normal)
            }
            else{
                cell.friendName.text = pendingReqData[indexPath.row].receiver_name
                if pendingReqData[indexPath.row].receiver_name != ""{
                    cell.friendNamePrefix.text = pendingReqData[indexPath.row].receiver_name?[0]
                }
                cell.btnAccept.setTitle("Resend", for: .normal)
            }
            
            let acceptTapGesture = CustomTapGesture(target: self, action: #selector(callAcceptReqAPI(_:)))
            acceptTapGesture.index = indexPath.row
            acceptTapGesture.section = indexPath.section
            acceptTapGesture.addBtn = cell.btnAccept
            cell.btnAccept.addGestureRecognizer(acceptTapGesture)
            
            let rejectTapGesture = CustomTapGesture(target: self, action: #selector(callRejectReqAPI(_:)))
            rejectTapGesture.arrFriendList = friendList
            rejectTapGesture.arrReqList = friendReqData
            rejectTapGesture.index = indexPath.row
            rejectTapGesture.section = indexPath.section
            cell.btnReject.addGestureRecognizer(rejectTapGesture)
            return cell
            
        default:
            return UITableViewCell()
        }
    }
}

fileprivate class CustomTapGesture: UITapGestureRecognizer {
    var arrFriendList = [FriendListModel]()
    var arrPendingReqList = [PendingFriendReqListModel]()
    var arrReqList = [ReceivedReqListModel]()
    var index = 0
    var section = 0
    var addBtn : SSSpinnerButton!
}
