import Foundation
import Alamofire
import WowonderMessengerSDK

class GroupChatManager {
    
    static let instance = GroupChatManager()
    
    func createGroup(session_Token: String, groupName: String, parts: String, type: String, avatar_data: Data?, completionBlock: @escaping (_ Success: CreateGroupModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let params = [
            API.Params.type : type,
            API.Params.group_name : groupName,
            API.Params.parts :parts,
            API.Params.server_key : API.SERVER_KEY.Server_Key
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.GROUP_CHATS_METHODS.GROUP_CHAT_API + session_Token
        print("urlString >>>>> ", urlString)
        let headers: HTTPHeaders = [
            "Content-type": "multipart/form-data"
        ]
        AF.upload(multipartFormData: { (multipartFormData) in
            for (key, value) in params {
                multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
            }
            if let avatarData = avatar_data {
                multipartFormData.append(avatarData, withName: "avatar", fileName: "avatar.jpg", mimeType: "image/png")
            }
        }, to: urlString, usingThreshold: UInt64.init(), method: .post, headers: headers).responseJSON(completionHandler: { (response) in
            print("Succesfully uploaded")
            if let res = response.value as? [String: Any] {
                print("Response = \(res)")
                guard let apiStatus = res["api_status"] else { return }
                if apiStatus is Int {
                    print("apiStatus Int = \(apiStatus)")
                    let data = try? JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try? JSONDecoder().decode(CreateGroupModel.self, from: data!)
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == "400" {
                        print("apiStatus String = \(apiStatus)")
                        let data = try? JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try? JSONDecoder().decode(ErrorModel.self, from: data!)
                        print("AuthError = \(result?.errors?.error_text ?? "")")
                        completionBlock(nil, result, nil, nil)
                    } else if apiStatusString == "404" {
                        let data = try? JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try? JSONDecoder().decode(ServerKeyErrorModel.self, from: data!)
                        print("AuthError = \(result?.errors?.error_text ?? "")")
                        completionBlock(nil, nil, result, nil)
                    }
                }
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, nil, nil, response.error)
            }
        })
    }
    
    func fetchGroups(session_Token: String, type: String, limit: Int, completionBlock: @escaping (_ Success: FetchGroupModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let params = [
            API.Params.type : type,
            API.Params.limit : limit,
            API.Params.server_key : API.SERVER_KEY.Server_Key
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.GROUP_CHATS_METHODS.GROUP_CHAT_API + session_Token
        print("urlString >>>>> ", urlString)
        AF.request(urlString, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            if let res = response.value as? [String: Any] {
                print("Response = \(res)")
                guard let apiStatus = res["api_status"] else { return }
                if apiStatus is Int {
                    print("apiStatus Int = \(apiStatus)")
                    let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try! JSONDecoder().decode(FetchGroupModel.self, from: data)
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == "400" {
                        print("apiStatus String = \(apiStatus)")
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, result, nil, nil)
                    } else if apiStatusString == "404" {
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ServerKeyErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, nil, result, nil)
                    }
                }
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, nil, nil, response.error)
            }
        }
    }
    
    func getGroupChats(group_Id: String, session_Token: String, completionBlock: @escaping (_ Success: GroupChatModel.GroupChatSuccessModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let convertUserId = Int(group_Id)
        let params = [
            API.Params.session_token : session_Token,
            API.Params.id : convertUserId ?? 0,
            API.Params.type : API.Params.fetch_messages,
            API.Params.server_key : API.SERVER_KEY.Server_Key,
            API.Params.limit: 1000
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.GROUP_CHATS_METHODS.GROUP_CHAT_API + session_Token
        print("urlString >>>>> ", urlString)
        AF.request(urlString, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            if let res = response.value as? [String: Any] {
                print("Response = \(res)")
                guard let apiStatus = res["api_status"] else { return }
                if apiStatus is Int {
                    print("apiStatus Int = \(apiStatus)")
                    let data = try? JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try? JSONDecoder().decode(GroupChatModel.GroupChatSuccessModel.self, from: data ?? Data())
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == "400" {
                        print("apiStatus String = \(apiStatus)")
                        let data = try? JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try? JSONDecoder().decode(ErrorModel.self, from: data ?? Data())
                        print("AuthError = \(result?.errors?.error_text ?? "")")
                        completionBlock(nil, result, nil, nil)
                    } else if apiStatusString == "404" {
                        let data = try? JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try? JSONDecoder().decode(ServerKeyErrorModel.self, from: data ?? Data())
                        print("AuthError = \(result?.errors?.error_text ?? "")")
                        completionBlock(nil, nil, result, nil)
                    }
                }
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, nil, nil, response.error)
            }
        }
    }
    
    func leaveGroup(group_Id: String, session_Token: String, type: String, completionBlock: @escaping (_ Success: GroupMessageModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let convertUserId = Int(group_Id)
        let params = [
            API.Params.session_token : session_Token,
            API.Params.id : convertUserId ?? 0,
            API.Params.type : type,
            API.Params.server_key : API.SERVER_KEY.Server_Key
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.GROUP_CHATS_METHODS.GROUP_CHAT_API + session_Token
        print("urlString >>>>> ", urlString)
        AF.request(urlString, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            if let res = response.value as? [String: Any] {
                print("Response = \(res)")
                guard let apiStatus = res["api_status"] else { return }
                if apiStatus is Int {
                    print("apiStatus Int = \(apiStatus)")
                    let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try! JSONDecoder().decode(GroupMessageModel.self, from: data)
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == "400" {
                        print("apiStatus String = \(apiStatus)")
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil,result,nil,nil)
                    } else if apiStatusString == "404" {
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ServerKeyErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil,nil,result,nil)
                    }
                }
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, nil, nil, response.error)
            }
        }
    }
    
    func deleteGroup(group_Id: String, session_Token: String, type: String, completionBlock: @escaping (_ Success: GroupMessageModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let convertUserId = Int(group_Id)
        let params = [
            API.Params.session_token : session_Token,
            API.Params.id : convertUserId ?? 0,
            API.Params.type : type,
            API.Params.server_key : API.SERVER_KEY.Server_Key
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.GROUP_CHATS_METHODS.GROUP_CHAT_API + session_Token
        print("urlString >>>>> ", urlString)
        AF.request(urlString, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            if let res = response.value as? [String: Any] {
                print("Response = \(res)")
                guard let apiStatus = res["api_status"] else { return }
                if apiStatus is Int {
                    print("apiStatus Int = \(apiStatus)")
                    let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try! JSONDecoder().decode(GroupMessageModel.self, from: data)
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == "400" {
                        print("apiStatus String = \(apiStatus)")
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, result, nil, nil)
                    } else if apiStatusString == "404" {
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ServerKeyErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, nil, result, nil)
                    }
                }
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, nil, nil, response.error)
            }
        }
    }
    
    func updateGroup(session_Token: String, groupName: String, groupId: String, type: String, avatar_data: Data?, completionBlock: @escaping (_ Success: UpdateGroupModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let params = [
            API.Params.type : type,
            API.Params.group_name : groupName,
            API.Params.id :groupId,
            API.Params.server_key : API.SERVER_KEY.Server_Key
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.GROUP_CHATS_METHODS.GROUP_CHAT_API + session_Token
        print("urlString >>>>> ", urlString)
        let headers: HTTPHeaders = [
            "Content-type": "multipart/form-data"
        ]
        AF.upload(multipartFormData: { (multipartFormData) in
            for (key, value) in params {
                multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
            }
            if let avatarData = avatar_data {
                multipartFormData.append(avatarData, withName: "avatar", fileName: "avatar.jpg", mimeType: "image/png")
            }
        }, to: urlString, usingThreshold: UInt64.init(), method: .post, headers: headers).responseJSON(completionHandler: { (response) in
            print("Succesfully uploaded")
            if let res = response.value as? [String: Any] {
                print("Response = \(res)")
                guard let apiStatus = res["api_status"] else { return }
                if apiStatus is Int {
                    print("apiStatus Int = \(apiStatus)")
                    let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try! JSONDecoder().decode(UpdateGroupModel.self, from: data)
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == "400" {
                        print("apiStatus String = \(apiStatus)")
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, result, nil, nil)
                    } else if apiStatusString == "404" {
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ServerKeyErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, nil, result, nil)
                    }
                }
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, nil, nil, response.error)
            }
        })
    }
    
    func addParticipants(group_Id: String, session_Token: String, type: String, part: String, completionBlock: @escaping (_ Success: GroupMessageModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let convertUserId = Int(group_Id)
        let params = [
            API.Params.session_token : session_Token,
            API.Params.id : convertUserId ?? 0,
            API.Params.type : type,
            API.Params.parts : part,
            API.Params.server_key : API.SERVER_KEY.Server_Key
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.GROUP_CHATS_METHODS.GROUP_CHAT_API + session_Token
        print("urlString >>>>> ", urlString)
        AF.request(urlString, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            if let res = response.value as? [String: Any] {
                print("Response = \(res)")
                guard let apiStatus = res["api_status"] else { return }
                if apiStatus is Int {
                    print("apiStatus Int = \(apiStatus)")
                    let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try! JSONDecoder().decode(GroupMessageModel.self, from: data)
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == "400" {
                        print("apiStatus String = \(apiStatus)")
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, result, nil, nil)
                    } else if apiStatusString == "404" {
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ServerKeyErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, nil, result, nil)
                    }
                }
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, nil, nil, response.error)
            }
        }
    }
    
    func removeParticipants(group_Id: String, session_Token: String, part: String, completionBlock: @escaping (_ Success: GroupMessageModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let convertUserId = Int(group_Id)
        let params = [
            API.Params.session_token : session_Token,
            API.Params.id : convertUserId ?? 0,
            API.Params.type : API.Params.remove_user,
            API.Params.parts : part,
            API.Params.server_key : API.SERVER_KEY.Server_Key
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.GROUP_CHATS_METHODS.GROUP_CHAT_API + session_Token
        print("urlString >>>>> ", urlString)
        AF.request(urlString, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            if let res = response.value as? [String: Any] {
                print("Response = \(res)")
                guard let apiStatus = res["api_status"] else { return }
                if apiStatus is Int {
                    print("apiStatus Int = \(apiStatus)")
                    let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try! JSONDecoder().decode(GroupMessageModel.self, from: data)
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == "400" {
                        print("apiStatus String = \(apiStatus)")
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, result, nil, nil)
                    } else if apiStatusString == "404" {
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ServerKeyErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, nil, result, nil)
                    }
                }
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, nil, nil, response.error)
            }
        }
    }
    
    func sendMessageToGroup(message_hash_id: Int, GroupId: String, text: String, session_Token: String, lat: Double, lag: Double, reply_id: String, completionBlock: @escaping (_ Success: SendMessageToGroupModel.SendMessageToGroupSuccessModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let covertedGroupId = Int(GroupId)
        let convertedHashID = "\(message_hash_id)"
        let params = [
            API.Params.message_hash_id : convertedHashID,
            API.Params.id : covertedGroupId as Any,
            API.Params.text : text,
            API.Params.type : API.Params.send,
            "lat": lat,
            "lng": lag,
            API.Params.server_key : API.SERVER_KEY.Server_Key,
            API.Params.reply_id : reply_id
        ] as [String : Any]
        print("params >>>>>> ", params)
        let urlString = API.GROUP_CHATS_METHODS.GROUP_CHAT_API + session_Token
        print("urlString >>>>> ", urlString)
        AF.request(urlString, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            if let res = response.value as? [String: Any] {
                guard let apiStatus = res["api_status"] else { return }
                if apiStatus is Int {
                    print("apiStatus Int = \(apiStatus)")
                    let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try! JSONDecoder().decode(SendMessageToGroupModel.SendMessageToGroupSuccessModel.self, from: data)
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == "400" {
                        print("apiStatus String = \(apiStatus)")
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, result, nil, nil)
                    } else if apiStatusString == "404" {
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ServerKeyErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, nil, result, nil)
                    }
                }
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, nil, nil, response.error)
            }
        }
    }
    
    func sendGroupChatData(message_hash_id: Int, groupId: String, session_Token: String, type: String, image_data: Data?, imageMimeType: String?, video_data: Data?, videoMimeType: String?, file_data: Data?, file_Extension: String?, fileMimeType: String?, audio_data: Data?, audio_Extension: String?, audioMimeType: String?, reply_id: String, completionBlock: @escaping (_ Success: SendMessageToGroupModel.SendMessageToGroupSuccessModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let covertedGroupId = Int(groupId) ?? 0
        let params = [
            API.Params.message_hash_id : message_hash_id,
            API.Params.type : API.Params.send,
            API.Params.id : covertedGroupId,
            API.Params.server_key : API.SERVER_KEY.Server_Key,
            API.Params.reply_id : reply_id
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.GROUP_CHATS_METHODS.GROUP_CHAT_API + session_Token
        print("urlString >>>>> ", urlString)
        let headers: HTTPHeaders = [
            "Content-type": "multipart/form-data"
        ]
        AF.upload(multipartFormData: { (multipartFormData) in
            for (key, value) in params {
                multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
            }
            if type == "image" {
                if let data = image_data {
                    multipartFormData.append(data, withName:"file", fileName: "image.jpg", mimeType: imageMimeType ?? "")
                }
            } else if type == "video" {
                if let data = video_data{
                    multipartFormData.append(data, withName: "file", fileName: "video.mp4", mimeType: videoMimeType ?? "")
                }
            } else if type == "audio" {
                if let data = audio_data {
                    multipartFormData.append(data, withName: "file", fileName: "audio.\(audio_Extension ?? "")", mimeType: audioMimeType ?? "")
                }
            } else {
                if let fileData = file_data {
                    multipartFormData.append(fileData, withName: "file", fileName: "file.\(file_Extension ?? "")", mimeType: fileMimeType ?? "")
                }
            }
        }, to: urlString, usingThreshold: UInt64.init(), method: .post, headers: headers).responseJSON(completionHandler: { (response) in
            print("Succesfully uploaded")
            if let res = response.value as? [String: Any] {
                print("Response = \(res)")
                guard let apiStatus = res["api_status"] else { return }
                if apiStatus is Int {
                    print("apiStatus Int = \(apiStatus)")
                    let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try! JSONDecoder().decode(SendMessageToGroupModel.SendMessageToGroupSuccessModel.self, from: data)
                    print("Success = \(result.apiStatus ?? 0)")
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == "400" {
                        print("apiStatus String = \(apiStatus)")
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, result, nil, nil)
                    } else if apiStatusString == "404" {
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ServerKeyErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, nil, result, nil)
                    }
                }
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, nil, nil, response.error)
            }
        })
    }
    
    func sendContactToGroup(message_hash_id: Int, groupId: String, jsonPayload: String, session_Token: String, contact: String = "1", reply_id: String, completionBlock: @escaping (_ Success: SendMessageToGroupModel.SendMessageToGroupSuccessModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let covertedGroupId = Int(groupId) ?? 0
        let convertedHashID = "\(message_hash_id)"
        let params = [
            API.Params.message_hash_id : convertedHashID,
            API.Params.id : covertedGroupId,
            API.Params.text : jsonPayload,
            API.Params.contact : contact,
            API.Params.type : API.Params.send,
            API.Params.server_key : API.SERVER_KEY.Server_Key,
            API.Params.reply_id : reply_id
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.GROUP_CHATS_METHODS.GROUP_CHAT_API + session_Token
        print("urlString >>>>> ", urlString)
        AF.request(urlString, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            if let res = response.value as? [String: Any] {
                guard let apiStatus = res["api_status"] else { return }
                if apiStatus is Int {
                    print("apiStatus Int = \(apiStatus)")
                    let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try! JSONDecoder().decode(SendMessageToGroupModel.SendMessageToGroupSuccessModel.self, from: data)
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == "400" {
                        print("apiStatus String = \(apiStatus)")
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, result, nil, nil)
                    } else if apiStatusString == "404" {
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ServerKeyErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, nil, result, nil)
                    }
                }
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, nil, nil, response.error)
            }
        }
    }
    
    func sendGIF(message_hash_id: Int, groupId: String, url: String, session_Token: String, reply_id: String, completionBlock: @escaping (_ Success: SendMessageModelOld?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let covertedGroupId = Int(groupId) ?? 0
        let convertedHashID = "\(message_hash_id)"
        let params = [
            API.Params.message_hash_id : convertedHashID,
            API.Params.id : covertedGroupId,
//            API.Params.Text : url,
            API.Params.gif : url,
            API.Params.type : API.Params.send,
            API.Params.server_key : API.SERVER_KEY.Server_Key,
            API.Params.reply_id : reply_id
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.GROUP_CHATS_METHODS.GROUP_CHAT_API + session_Token
        print("urlString >>>>> ", urlString)
        AF.request(urlString, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            if let res = response.value as? [String: Any] {
                guard let apiStatus = res["api_status"] else { return }
                if apiStatus is Int {
                    print("apiStatus Int = \(apiStatus)")
                    let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try! JSONDecoder().decode(SendMessageModelOld.self, from: data)
                    print("Success = \(result.messageData ?? [])")
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == "400" {
                        print("apiStatus String = \(apiStatus)")
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, result, nil, nil)
                    } else if apiStatusString == "404" {
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ServerKeyErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, nil, result, nil)
                    }
                }
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, nil, nil, response.error)
            }
        }
    }
    
    func sendSticker(message_hash_id: Int, groupId: String, url: String, sticker_id: String, session_Token: String, reply_id: String, completionBlock: @escaping (_ Success: SendMessageModelOld?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let covertedGroupId = Int(groupId) ?? 0
        let convertedHashID = "\(message_hash_id)"
        let params = [
            API.Params.message_hash_id: convertedHashID,
            API.Params.id: covertedGroupId,
            API.Params.image_url: url,
            API.Params.sticker_id: sticker_id,
            API.Params.type: API.Params.send,
            API.Params.server_key: API.SERVER_KEY.Server_Key,
            API.Params.reply_id: reply_id
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.GROUP_CHATS_METHODS.GROUP_CHAT_API + session_Token
        print("urlString >>>>> ", urlString)
        AF.request(urlString, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            if let res = response.value as? [String: Any] {
                guard let apiStatus = res["api_status"] else { return }
                if apiStatus is Int {
                    print("apiStatus Int = \(apiStatus)")
                    let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try! JSONDecoder().decode(SendMessageModelOld.self, from: data)
                    print("Success = \(result.messageData ?? [])")
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == "400" {
                        print("apiStatus String = \(apiStatus)")
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, result, nil, nil)
                    } else if apiStatusString == "404" {
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ServerKeyErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, nil, result, nil)
                    }
                }
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, nil, nil, response.error)
            }
        }
    }
    
    func muteGroupChat(muteType: String, mute: String, chat_id: String, completionBlock: @escaping (_ Success: ApiMessageModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let params = [
            API.Params.server_key : API.SERVER_KEY.Server_Key,
            API.Params.chat_id: chat_id,
            API.Params.type: API.Params.group,
            muteType: mute
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.MUTE_API.MUTE_API + (AppInstance.instance.sessionId ?? "")
        print("urlString >>>>> ", urlString)
        AF.request(urlString, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            if let res = response.value as? [String : Any] {
                print("Response = \(res)")
                guard let apiStatus = res["api_status"] else { return }
                if apiStatus is Int {
                    print("apiStatus Int = \(apiStatus)")
                    let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try! JSONDecoder().decode(ApiMessageModel.self, from: data)
                    print("Success = \(result.message ?? "")")
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == "400" {
                        print("apiStatus String = \(apiStatus)")
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, result, nil, nil)
                    } else if apiStatusString == "404" {
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ServerKeyErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, nil, result, nil)
                    }
                }
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, nil, nil, response.error)
            }
        }
    }
    
    func getSearchMessage(group_id: String, text: String, completionBlock: @escaping (_ Success: SearchMessageModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let params = [
            API.Params.server_key : API.SERVER_KEY.Server_Key,
            API.Params.type: API.Params.search,
            API.Params.group_id : group_id,
            API.Params.text: text
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.Chat_Methods.SEARCH_MESSAGE_API + AppInstance.instance._sessionId
        print("urlString >>>>> ", urlString)
        AF.request(urlString, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            if let res = response.value as? [String : Any] {
                print("Response = \(res)")
                guard let apiStatus = res["api_status"] else { return }
                if apiStatus is Int {
                    print("apiStatus Int = \(apiStatus)")
                    let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try! JSONDecoder().decode(SearchMessageModel.self, from: data)
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == "400" {
                        print("apiStatus String = \(apiStatus)")
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, result, nil, nil)
                    } else if apiStatusString == "404" {
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ServerKeyErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, nil, result, nil)
                    }
                }
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, nil, nil, response.error)
            }
        }
    }
    
}
