//
//  PickFriendViewModel.swift


import Foundation
import UIKit

class PickFriendViewModel : NSObject{
    
    var arrFriendListData : BoxBind<[FriendListModel]> = BoxBind([FriendListModel]())
    var arrFriendId : BoxBind<[String]> = BoxBind([String]())
    
    override init() {
        super.init()
        self.callFriendListAPI()
    }
    
    func callFriendListAPI(){
        APIDataManager.shared.getFriendListAPI { success in
            self.arrFriendListData.value = success
        } failure: { (error) in
            debugPrint("Error Occured",error)
        }
    }
    
    func callSendImageAPI(friendIds : String, image : UIImage, completion : @escaping (Bool) -> ()){
        APIDataManager.shared.getImageUploadAPI(friendIds: friendIds, image: image) { success in
            completion(success)
        }
    }
    
    func callResendImageAPI(imageId : String, friendIds : String, completion : @escaping((Bool)->())){
        APIDataManager.shared.resendImageAPI(frinedIds: friendIds, imageId: imageId) { success,message in
            completion(success)
            if !success{
                Utilities.showAlertView(nil, message) { _ in}
            }
        }
    }
    
    //MARK: - Delegate and Datasouce
    
    func getCellCountForDisplay() -> Int{
        return self.arrFriendListData.value.count
    }
    
    func prepareCellForDisplay(tableView: UITableView, indexPath : IndexPath, friendList : [FriendListModel]) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: PickFriendTVCell.identifier, for: indexPath) as! PickFriendTVCell
        cell.friendNameLbl.text = friendList[indexPath.row].full_name
        if friendList[indexPath.row].full_name != ""{
            cell.tagName.text = friendList[indexPath.row].full_name?[0]
        }
        if friendList[indexPath.row].isSelected ?? false{
            cell.selectedImageView.image = UIImage(named: "selected_icon")
        }
        else{
            cell.selectedImageView.image = UIImage(named: "unselected_icon")
        }
        return cell
    }
    
    func getSelectAction(tableView : UITableView, indexPath: IndexPath, friendList : [FriendListModel]){
        if friendList[indexPath.row].isSelected ?? false{
            self.arrFriendListData.value[indexPath.row].isSelected = false
            self.arrFriendId.value.removeObject(object: String(friendList[indexPath.row].friend_id ?? 0))
        }
        else{
            self.arrFriendListData.value[indexPath.row].isSelected = true
            self.arrFriendId.value.append(String(friendList[indexPath.row].friend_id ?? 0))
        }
    }
}
