//
//  PinnedAndFavouriteMessageVC.swift
//  WoWonder
//
//  Created by Fs on 03/10/22.
//  Copyright © 2022 ScriptSun. All rights reserved.
//

import UIKit
import AVFoundation
import AVKit
import Async
import Toast_Swift
import MapKit
import SafariServices
import WowonderMessengerSDK
import SDWebImage
import Contacts
import ContactsUI

class PinnedAndFavouriteMessageVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var headerTitleLabel: UILabel!
    @IBOutlet weak var tableView: UITableView!
    
    // MARK: - Properties
    
    var chatModel: Chats?
    var messagesArray = [MessageModel]()
    private var isColor = ""
    var isPinnedMessages = false
    var headerTitle = ""
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initialConfig()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        
        AudioPlayerHelper.shared.delegate = self
        let objColor = UserDefaults.standard.value(forKey: "ColorTheme")
        self.isColor = objColor as? String ?? ""
        self.navigationController?.navigationBar.isHidden = true
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        AudioPlayerHelper.shared.stopAudioPlayer()
    }
    
    // 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.headerTitleLabel.text = self.headerTitle
        AudioPlayerHelper.shared.delegate = self
        let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressed))
        self.tableView.addGestureRecognizer(longPressRecognizer)
        self.registerCell()
    }
    
    // Register Cell
    func registerCell() {
        self.tableView.delegate = self
        self.tableView.dataSource = self
        if #available(iOS 15.0, *) {
            UITableView.appearance().isPrefetchingEnabled = false
        }
        self.tableView.register(UINib(resource: R.nib.leftTextTableViewCell), forCellReuseIdentifier: R.reuseIdentifier.leftTextTableViewCell.identifier)
        self.tableView.register(UINib(resource: R.nib.rightTextTableViewCell), forCellReuseIdentifier: R.reuseIdentifier.rightTextTableViewCell.identifier)
        self.tableView.register(UINib(resource: R.nib.rightImageTableViewCell), forCellReuseIdentifier: R.reuseIdentifier.rightImageTableViewCell.identifier)
        self.tableView.register(UINib(resource: R.nib.leftImageTableViewCell), forCellReuseIdentifier: R.reuseIdentifier.leftImageTableViewCell.identifier)
        self.tableView.register(UINib(resource: R.nib.leftDocumentTableViewCell), forCellReuseIdentifier: R.reuseIdentifier.leftDocumentTableViewCell.identifier)
        self.tableView.register(UINib(resource: R.nib.rightDocumentTableViewCell), forCellReuseIdentifier: R.reuseIdentifier.rightDocumentTableViewCell.identifier)
        self.tableView.register(UINib(resource: R.nib.leftVideoTableViewCell), forCellReuseIdentifier: R.reuseIdentifier.leftVideoTableViewCell.identifier)
        self.tableView.register(UINib(resource: R.nib.rightVideoTableViewCell), forCellReuseIdentifier: R.reuseIdentifier.rightVideoTableViewCell.identifier)
        self.tableView.register(UINib(resource: R.nib.rightGifTableViewCell), forCellReuseIdentifier: R.reuseIdentifier.rightGifTableViewCell.identifier)
        self.tableView.register(UINib(resource: R.nib.leftGifTableViewCell), forCellReuseIdentifier: R.reuseIdentifier.leftGifTableViewCell.identifier)
        self.tableView.register(UINib(resource: R.nib.leftLocationTableViewCell), forCellReuseIdentifier: R.reuseIdentifier.leftLocationTableViewCell.identifier)
        self.tableView.register(UINib(resource: R.nib.rightLocationTableViewCell), forCellReuseIdentifier: R.reuseIdentifier.rightLocationTableViewCell.identifier)
        self.tableView.register(UINib(resource: R.nib.leftAudioTableViewCell), forCellReuseIdentifier: R.reuseIdentifier.leftAudioTableViewCell.identifier)
        self.tableView.register(UINib(resource: R.nib.rightAudioTableViewCell), forCellReuseIdentifier: R.reuseIdentifier.rightAudioTableViewCell.identifier)
        self.tableView.register(UINib(resource: R.nib.leftContactTableViewCell), forCellReuseIdentifier: R.reuseIdentifier.leftContactTableViewCell.identifier)
        self.tableView.register(UINib(resource: R.nib.rightContactTableViewCell), forCellReuseIdentifier: R.reuseIdentifier.rightContactTableViewCell.identifier)
        self.tableView.register(UINib(resource: R.nib.rightStickerCell), forCellReuseIdentifier: R.reuseIdentifier.rightStickerCell.identifier)
        self.tableView.register(UINib(resource: R.nib.leftStickerCell), forCellReuseIdentifier: R.reuseIdentifier.leftStickerCell.identifier)
    }
    
    // TableView longPressed Click
    @objc func longPressed(sender: UILongPressGestureRecognizer) {
        let objSender = sender.location(in: self.tableView)
        let indexPath = self.tableView.indexPathForRow(at: objSender)
        let objCopyMessageArray = self.messagesArray[indexPath?.row ?? 0]
        if let newVC = R.storyboard.chat.pinnedAndFavouriteMessageOptionVC() {
            newVC.delegate = self
            newVC.indexPath = indexPath ?? IndexPath()
            if objCopyMessageArray.type == "right_text" || objCopyMessageArray.type == "left_text" {
                if (Double(objCopyMessageArray.lat ?? "0.0") ?? 0.0) > 0.0 || Double(objCopyMessageArray.lng ?? "0.0") ?? 0.0 > 0.0 {
                    newVC.isCopy = false
                } else {
                    newVC.isCopy = true
                }
            } else {
                newVC.isCopy = false
            }
            newVC.isRightUser = AppInstance.instance.userId == self.messagesArray[indexPath?.row ?? 0].messageUser?.user_id
            newVC.message = objCopyMessageArray
            self.present(newVC, animated: true)
        }
    }
    
}

// MARK: - Extensions

// MARK: Api Call
extension PinnedAndFavouriteMessageVC {
    
    // Delete Message Api Call
    private func deleteMessage(messageID: String, indexPath: Int) {
        let sessionID = AppInstance.instance._sessionId
        Async.background {
            ChatManager.instance.deleteChatMessage(messageId: messageID, session_Token: sessionID, completionBlock: { (success, sessionError, serverError, error) in
                if success != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            if let chat_id = self.chatModel?.chat_id {
                                if self.messagesArray[indexPath].pin == "yes" {
                                    self.pinMessageApi(message_id: self.messagesArray[indexPath].id ?? "", pin: "no", chat_id: chat_id)
                                }
                                if self.messagesArray[indexPath].fav == "yes" {
                                    self.favMessageApi(message_id: self.messagesArray[indexPath].id ?? "", fav: "no", chat_id: chat_id)
                                }
                            }
                            let appDelegate = (UIApplication.shared.delegate) as? AppDelegate
                            let context = appDelegate?.persistentContainer.viewContext
                            guard let msg = Messages.getMessageByID(self.messagesArray[indexPath].id ?? "") else { return }
                            context?.delete(msg)
                            do {
                                try context?.save()
                            } catch {
                                print("failed so save data after deleting object")
                            }
                            self.messagesArray.remove(at: indexPath)
                            self.tableView.reloadData()
                        }
                    }
                } 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)
                        }
                    }
                }
            })
        }
    }
    
    // Pin Message Api Call
    private func pinMessageApi(message_id: String, pin: String, chat_id: String) {
        Async.background {
            ChatManager.instance.pinMessage(message_id: message_id, pin: pin, chat_id: chat_id, completionBlock: { (success, sessionError, serverError, error) in
                if success != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            print(success?.message ?? "")
                            if let chat_id = self.chatModel?.chat_id {
                                if self.isPinnedMessages {
                                    self.getPinMessages(chat_id: chat_id)
                                } else {
                                    self.getFavMessages(chat_id: chat_id)
                                }
                            }
                        }
                    }
                } 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)
                        }
                    }
                }
            })
        }
    }
    
    // Get Pin Message Api Call
    private func getPinMessages(chat_id: String) {
        Async.background {
            ChatManager.instance.getPinMessage(chat_id: chat_id, completionBlock: { (success, sessionError, serverError, error) in
                if success != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            self.messagesArray = success?.data ?? []
                            self.tableView.reloadData()
                        }
                    }
                } 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)
                        }
                    }
                }
            })
        }
    }
    
    // Fav Message Api Call
    private func favMessageApi(message_id: String, fav: String, chat_id: String) {
        Async.background {
            ChatManager.instance.favMessage(message_id: message_id, fav: fav, chat_id: chat_id, completionBlock: { (success, sessionError, serverError, error) in
                if success != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            print(success?.message ?? "")
                            if let chat_id = self.chatModel?.chat_id {
                                if self.isPinnedMessages {
                                    self.getPinMessages(chat_id: chat_id)
                                } else {
                                    self.getFavMessages(chat_id: chat_id)
                                }
                            }
                        }
                    }
                } 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)
                        }
                    }
                }
            })
        }
    }
    
    // Get Fav Message Api Call
    private func getFavMessages(chat_id: String) {
        Async.background {
            ChatManager.instance.getFavMessage(chat_id: chat_id, completionBlock: { (success, sessionError, serverError, error) in
                if success != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            self.messagesArray = success?.data ?? []
                            self.tableView.reloadData()
                        }
                    }
                } 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)
                        }
                    }
                }
            })
        }
    }
    
}

// MARK: TableView Setup
extension PinnedAndFavouriteMessageVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.messagesArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let objChatList = self.messagesArray[indexPath.row]
        guard let type = objChatList.type else { return UITableViewCell() }
        switch type {
        case "left_text":
            if AppInstance.instance.userId == self.messagesArray[indexPath.row].messageUser?.user_id {
                let lat = Double(objChatList.lat ?? "0.0") ?? 0.0
                let long = Double(objChatList.lng ?? "0.0") ?? 0.0
                if lat > 0.0 || long > 0.0 {
                    let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.rightLocationTableViewCell.identifier, for: indexPath) as! RightLocationTableViewCell
                    self.setRightLocationData(lat: lat, long: long, cell: cell, indexPathForCell: indexPath)
                    return cell
                } else {
                    let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.rightTextTableViewCell.identifier, for: indexPath) as! RightTextTableViewCell
                    self.setRightTextData(cell: cell, indexPathForCell: indexPath)
                    return cell
                }
            } else {
                let lat = Double(objChatList.lat ?? "0.0") ?? 0.0
                let long = Double(objChatList.lng ?? "0.0") ?? 0.0
                if lat > 0.0 || long > 0.0 {
                    let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.leftLocationTableViewCell.identifier, for: indexPath) as! LeftLocationTableViewCell
                    self.setLeftLocationData(lat: lat, long: long, cell: cell, indexPathForCell: indexPath)
                    return cell
                } else {
                    let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.leftTextTableViewCell.identifier, for: indexPath) as! LeftTextTableViewCell
                    self.setLeftTextData(cell: cell, indexPathForCell: indexPath)
                    return cell
                }
            }
        case "left_image":
            if AppInstance.instance.userId == self.messagesArray[indexPath.row].messageUser?.user_id {
                let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.rightImageTableViewCell.identifier, for: indexPath) as! RightImageTableViewCell
                self.setRightImageData(cell: cell, indexPathForCell: indexPath)
                return cell
            } else {
                let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.leftImageTableViewCell.identifier, for: indexPath) as! LeftImageTableViewCell
                self.setLeftImageData(cell: cell, indexPathForCell: indexPath)
                return cell
            }
        case "left_video":
            if AppInstance.instance.userId == self.messagesArray[indexPath.row].messageUser?.user_id {
                let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.rightVideoTableViewCell.identifier, for: indexPath) as! RightVideoTableViewCell
                self.setRightVideoData(cell: cell, indexPathForCell: indexPath)
                return cell
            } else {
                let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.leftVideoTableViewCell.identifier, for: indexPath) as! LeftVideoTableViewCell
                self.setLeftVideoData(cell: cell, indexPathForCell: indexPath)
                return cell
            }
        case "left_gif":
            if AppInstance.instance.userId == self.messagesArray[indexPath.row].messageUser?.user_id {
                let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.rightGifTableViewCell.identifier, for: indexPath) as! RightGifTableViewCell
                self.setRightGifData(cell: cell, indexPathForCell: indexPath)
                return cell
            } else {
                let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.leftGifTableViewCell.identifier, for: indexPath) as! LeftGifTableViewCell
                self.setLeftGifData(cell: cell, indexPathForCell: indexPath)
                return cell
            }
        case "left_contact":
            if AppInstance.instance.userId == self.messagesArray[indexPath.row].messageUser?.user_id {
                let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.rightContactTableViewCell.identifier, for: indexPath) as! RightContactTableViewCell
                self.setRightContactData(cell: cell, indexpathForCell: indexPath)
                return cell
            } else {
                let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.leftContactTableViewCell.identifier, for: indexPath) as! LeftContactTableViewCell
                self.setLeftContactData(cell: cell, indexpathForCell: indexPath)
                return cell
            }
        case "left_file":
            if AppInstance.instance.userId == self.messagesArray[indexPath.row].messageUser?.user_id {
                let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.rightDocumentTableViewCell.identifier, for: indexPath) as! RightDocumentTableViewCell
                self.setRightDocumentData(cell: cell, indexPathForCell: indexPath)
                return cell
            } else {
                let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.leftDocumentTableViewCell.identifier, for: indexPath) as! LeftDocumentTableViewCell
                self.setLeftDocumentData(cell: cell, indexPathForCell: indexPath)
                return cell
            }
        case "left_audio":
            if AppInstance.instance.userId == self.messagesArray[indexPath.row].messageUser?.user_id {
                let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.rightAudioTableViewCell.identifier, for: indexPath) as! RightAudioTableViewCell
                self.setRightAudioData(cell: cell, indexPathForCell: indexPath)
                return cell
            } else {
                let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.leftAudioTableViewCell.identifier, for: indexPath) as! LeftAudioTableViewCell
                self.setLeftAudioData(cell: cell, indexPathForCell: indexPath)
                return cell
            }
        case "left_sticker":
            if AppInstance.instance.userId == self.messagesArray[indexPath.row].messageUser?.user_id {
                let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.rightStickerCell.identifier, for: indexPath) as! RightStickerCell
                self.setRightStickerData(cell: cell, indexPathForCell: indexPath)
                return cell
            } else {
                let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.leftStickerCell.identifier, for: indexPath) as! LeftStickerCell
                self.setLeftStickerData(cell: cell, indexPathForCell: indexPath)
                return cell
            }
        default:
            return UITableViewCell()
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    // Set Left Text Data
    private func setLeftTextData(cell: LeftTextTableViewCell, indexPathForCell: IndexPath) {
        cell.swipeRecognizer.isEnabled = false
        let objChatList = self.messagesArray[indexPathForCell.row]
        cell.forwardedView.isHidden = objChatList.forward == "0"
        cell.userStackView.isHidden = true
        cell.replyMessageView.isHidden = true
        cell.replyStoryView.isHidden = true
        cell.masageTextLabel.text = objChatList.text ?? ""
        cell.messageTimeLabel.text = objChatList.time?.timeStampStringToTime()
        if objChatList._reaction == "" {
            cell.reactionImageView.isHidden = true
        } else {
            cell.reactionImageView.isHidden = false
            cell.reactionImageView.image = self.setReactionEmoji(type: objChatList._reaction)
        }
        if objChatList.fav == "on" {
            cell.starImageView.isHidden = false
        } else {
            cell.starImageView.isHidden = true
        }
        // cell.messageView.backgroundColor = UIColor(hex: "#F2F2F2")
    }
    
    // Set Right Text Data
    private func setRightTextData(cell: RightTextTableViewCell, indexPathForCell: IndexPath) {
        cell.swipeRecognizer.isEnabled = false
        let objChatList = self.messagesArray[indexPathForCell.row]
        cell.forwardedView.isHidden = objChatList.forward == "0"
        cell.replyMessageView.isHidden = true
        cell.replyStoryView.isHidden = true
        cell.messaageTextLabel.text = objChatList.text ?? ""
        cell.messageTimeLabel.text = objChatList.time?.timeStampStringToTime()
        if objChatList._reaction == "" {
            cell.reactionImageView.isHidden = true
        } else {
            cell.reactionImageView.isHidden = false
            cell.reactionImageView.image = self.setReactionEmoji(type: objChatList._reaction)
        }
        if objChatList.fav == "on" {
            cell.starImageVIew.isHidden = false
        } else {
            cell.starImageVIew.isHidden = true
        }
        if isColor != "" {
            cell.messageView.backgroundColor = UIColor(hex: isColor)
        } else {
            cell.messageView.backgroundColor = UIColor(hex: "#C83747")
        }
        if objChatList.seen == "0" {
            cell.lastSeenImage.image = UIImage(named: "ic_seenCheck")?.withRenderingMode(.alwaysTemplate)
            if isColor != "" {
                cell.lastSeenImage.tintColor = UIColor(hex: isColor)
            } else {
                cell.lastSeenImage.tintColor = UIColor(hex: "C83747")
            }
        } else {
            cell.lastSeenImage.image = UIImage(named: "ic_seen")?.withRenderingMode(.alwaysTemplate)
            if isColor != "" {
                cell.lastSeenImage.tintColor = UIColor(hex: isColor)
            } else {
                cell.lastSeenImage.tintColor = UIColor(hex: "C83747")
            }
        }
    }
    
    // Set Left Location Data
    private func setLeftLocationData(lat: Double, long: Double, cell: LeftLocationTableViewCell, indexPathForCell: IndexPath) {
        cell.swipeRecognizer.isEnabled = false
        let objChatList = messagesArray[indexPathForCell.row]
        cell.forwardedView.isHidden = objChatList.forward == "0"
        cell.userStackView.isHidden = true
        cell.replyMessageView.isHidden = true
        cell.replyStoryView.isHidden = true
        cell.messageTimeLabel.text = objChatList.time?.timeStampStringToTime()
        cell.configureMapView(lat: lat, long: long)
        cell.mapButton.tag = indexPathForCell.row
        cell.mapButton.addTarget(self, action: #selector(self.setLocationNavigaction), for: .touchUpInside)
        if objChatList._reaction == "" {
            cell.reactionImageView.isHidden = true
        } else {
            cell.reactionImageView.isHidden = false
            cell.reactionImageView.image = self.setReactionEmoji(type: objChatList._reaction)
        }
        if objChatList.fav == "on" {
            cell.starImageView.isHidden = false
        } else {
            cell.starImageView.isHidden = true
        }
        // cell.messageView.backgroundColor = UIColor(hex: "#F2F2F2")
    }
    
    // Set Right Location Data
    private func setRightLocationData(lat: Double, long: Double, cell: RightLocationTableViewCell, indexPathForCell: IndexPath) {
        cell.swipeRecognizer.isEnabled = false
        let objChatList = messagesArray[indexPathForCell.row]
        cell.forwardedView.isHidden = objChatList.forward == "0"
        cell.replyMessageView.isHidden = true
        cell.replyStoryView.isHidden = true
        cell.messageTimeLabel.text = objChatList.time?.timeStampStringToTime()
        cell.configureMapView(lat: lat, long: long)
        cell.mapButton.tag = indexPathForCell.row
        cell.mapButton.addTarget(self, action: #selector(self.setLocationNavigaction), for: .touchUpInside)
        if objChatList._reaction == "" {
            cell.reactionImageView.isHidden = true
        } else {
            cell.reactionImageView.isHidden = false
            cell.reactionImageView.image = self.setReactionEmoji(type: objChatList._reaction)
        }
        if objChatList.fav == "on" {
            cell.starImageView.isHidden = false
        } else {
            cell.starImageView.isHidden = true
        }
        if isColor != "" {
            cell.messageView.backgroundColor = UIColor(hex: isColor)
        } else {
            cell.messageView.backgroundColor = UIColor(hex: "#C83747")
        }
        if objChatList.seen == "0" {
            cell.lastSeenImage.image = UIImage(named: "ic_seenCheck")?.withRenderingMode(.alwaysTemplate)
            if isColor != "" {
                cell.lastSeenImage.tintColor = UIColor(hex: isColor)
            } else {
                cell.lastSeenImage.tintColor = UIColor(hex: "C83747")
            }
        } else {
            cell.lastSeenImage.image = UIImage(named: "ic_seen")?.withRenderingMode(.alwaysTemplate)
            if isColor != "" {
                cell.lastSeenImage.tintColor = UIColor(hex: isColor)
            } else {
                cell.lastSeenImage.tintColor = UIColor(hex: "C83747")
            }
        }
    }
    
    // Set Left Image Data
    private func setLeftImageData(cell: LeftImageTableViewCell, indexPathForCell: IndexPath) {
        cell.swipeRecognizer.isEnabled = false
        let objChatList = self.messagesArray[indexPathForCell.row]
        cell.forwardedView.isHidden = objChatList.forward == "0"
        cell.userStackView.isHidden = true
        cell.replyMessageView.isHidden = true
        cell.replyStoryView.isHidden = true
        let imageUrl = URL(string: objChatList.media ?? "")
        cell.imageUrl = imageUrl
        if AppInstance.instance.isDownloadImage == false {
            if let imageURL = imageUrl, let localURL = MediaDownloader.shared.getCachedLocalURL(for: imageURL),
               FileManager.default.fileExists(atPath: localURL.path) {
                cell.loadImage(from: localURL)
                cell.blurView.isHidden = true // Hide download button
            } else {
                let indicator = SDWebImageActivityIndicator.medium
                cell.sendImageView.sd_imageIndicator = indicator
                DispatchQueue.global(qos: .userInteractive).async {
                    cell.sendImageView.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: ""))
                }
            }
        } else {
            cell.blurView.isHidden = true
            let indicator = SDWebImageActivityIndicator.medium
            cell.sendImageView.sd_imageIndicator = indicator
            DispatchQueue.global(qos: .userInteractive).async {
                cell.sendImageView.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: ""))
            }
        }
        cell.messageTimeLabel.text = objChatList.time?.timeStampStringToTime()
        cell.messageImageButton.tag = indexPathForCell.row
        cell.messageImageButton.addTarget(self, action: #selector(self.clickImageClick), for: .touchUpInside)
        if objChatList._reaction == "" {
            cell.reactionImageView.isHidden = true
        } else {
            cell.reactionImageView.isHidden = false
            cell.reactionImageView.image = self.setReactionEmoji(type: objChatList._reaction)
        }
        if objChatList.fav == "on" {
            cell.starImageView.isHidden = false
        } else {
            cell.starImageView.isHidden = true
        }
        // cell.messageView.backgroundColor = UIColor(hex: "#F2F2F2")
    }
    
    // Set Right Image Data
    private func setRightImageData(cell: RightImageTableViewCell, indexPathForCell: IndexPath) {
        cell.swipeRecognizer.isEnabled = false
        let objChatList = self.messagesArray[indexPathForCell.row]
        cell.forwardedView.isHidden = objChatList.forward == "0"
        cell.replyMessageView.isHidden = true
        cell.replyStoryView.isHidden = true
        let imageUrl = URL(string: objChatList.media ?? "")
        cell.imageUrl = imageUrl
        if AppInstance.instance.isDownloadImage == false {
            if let imageURL = imageUrl, let localURL = MediaDownloader.shared.getCachedLocalURL(for: imageURL),
               FileManager.default.fileExists(atPath: localURL.path) {
                cell.loadImage(from: localURL)
                cell.blurView.isHidden = true // Hide download button
            } else {
                let indicator = SDWebImageActivityIndicator.medium
                cell.sendImageView.sd_imageIndicator = indicator
                DispatchQueue.global(qos: .userInteractive).async {
                    cell.sendImageView.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: ""))
                }
            }
        } else {
            cell.blurView.isHidden = true
            let indicator = SDWebImageActivityIndicator.medium
            cell.sendImageView.sd_imageIndicator = indicator
            DispatchQueue.global(qos: .userInteractive).async {
                cell.sendImageView.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: ""))
            }
        }
        cell.messageTimeLabel.text = objChatList.time?.timeStampStringToTime()
        cell.messageImageButton.tag = indexPathForCell.row
        cell.messageImageButton.addTarget(self, action: #selector(self.clickImageClick), for: .touchUpInside)
        if objChatList._reaction == "" {
            cell.reactionImageView.isHidden = true
        } else {
            cell.reactionImageView.isHidden = false
            cell.reactionImageView.image = self.setReactionEmoji(type: objChatList._reaction)
        }
        if objChatList.fav == "on" {
            cell.starImageView.isHidden = false
        } else {
            cell.starImageView.isHidden = true
        }
        if isColor != "" {
            cell.messageView.backgroundColor = UIColor(hex: isColor)
        } else {
            cell.messageView.backgroundColor = UIColor(hex: "#C83747")
        }
        if objChatList.seen == "0" {
            cell.lastSeenImage.image = UIImage(named: "ic_seenCheck")?.withRenderingMode(.alwaysTemplate)
            if isColor != "" {
                cell.lastSeenImage.tintColor = UIColor(hex: isColor)
            } else {
                cell.lastSeenImage.tintColor = UIColor(hex: "C83747")
            }
        } else {
            cell.lastSeenImage.image = UIImage(named: "ic_seen")?.withRenderingMode(.alwaysTemplate)
            if isColor != "" {
                cell.lastSeenImage.tintColor = UIColor(hex: isColor)
            } else {
                cell.lastSeenImage.tintColor = UIColor(hex: "C83747")
            }
        }
    }
    
    // Set Left Video Data
    private func setLeftVideoData(cell: LeftVideoTableViewCell, indexPathForCell: IndexPath) {
        cell.swipeRecognizer.isEnabled = false
        let objChatList = self.messagesArray[indexPathForCell.row]
        cell.forwardedView.isHidden = objChatList.forward == "0"
        cell.userStackView.isHidden = true
        cell.replyMessageView.isHidden = true
        cell.replyStoryView.isHidden = true
        cell.messageTimeLabel.text = objChatList.time?.timeStampStringToTime()
        let videoUrl = URL(string: objChatList.media ?? "")
        cell.videoUrl = videoUrl
        cell.videoImageView.image = UIImage(named: "")
        if AppInstance.instance.isDownloadVideo == false {
            if let videoUrl = videoUrl, let localURL = MediaDownloader.shared.getCachedLocalURL(for: videoUrl),
               FileManager.default.fileExists(atPath: localURL.path) {
                DispatchQueue.global(qos: .userInteractive).async {
                    AppInstance.instance.generateThumbnail(from: localURL, completion: { image in
                        DispatchQueue.main.async {
                            if let image = image {
                                cell.videoImageView.image = image
                            } else {
                                cell.videoImageView.image = UIImage(named: "")
                            }
                        }
                    })
                }
                cell.blurView.isHidden = true // Hide download button
            } else {
                DispatchQueue.global(qos: .userInteractive).async {
                    AppInstance.instance.generateThumbnail(from: videoUrl, completion: { image in
                        DispatchQueue.main.async {
                            if let image = image {
                                cell.videoImageView.image = image
                            } else {
                                cell.videoImageView.image = UIImage(named: "")
                            }
                        }
                    })
                }
            }
        } else {
            cell.blurView.isHidden = true
            DispatchQueue.global(qos: .userInteractive).async {
                AppInstance.instance.generateThumbnail(from: videoUrl, completion: { image in
                    DispatchQueue.main.async {
                        if let image = image {
                            cell.videoImageView.image = image
                        } else {
                            cell.videoImageView.image = UIImage(named: "")
                        }
                    }
                })
            }
        }
        cell.messageVideoButton.tag = indexPathForCell.row
        cell.messageVideoButton.addTarget(self, action: #selector(self.clickVideoButton), for: .touchUpInside)
        if objChatList._reaction == "" {
            cell.reactionImageView.isHidden = true
        } else {
            cell.reactionImageView.isHidden = false
            cell.reactionImageView.image = self.setReactionEmoji(type: objChatList._reaction)
        }
        if objChatList.fav == "on" {
            cell.starImageView.isHidden = false
        } else {
            cell.starImageView.isHidden = true
        }
        // cell.messageView.backgroundColor = UIColor(hex: "#F2F2F2")
    }
    
    // Set Right Video Data
    private func setRightVideoData(cell: RightVideoTableViewCell, indexPathForCell: IndexPath) {
        cell.swipeRecognizer.isEnabled = false
        let objChatList = self.messagesArray[indexPathForCell.row]
        cell.forwardedView.isHidden = objChatList.forward == "0"
        cell.replyMessageView.isHidden = true
        cell.replyStoryView.isHidden = true
        cell.messageTimeLabel.text = objChatList.time?.timeStampStringToTime()
        let videoUrl = URL(string: objChatList.media ?? "")
        cell.videoUrl = videoUrl
        cell.videoImageView.image = UIImage(named: "")
        if AppInstance.instance.isDownloadVideo == false {
            if let videoUrl = videoUrl, let localURL = MediaDownloader.shared.getCachedLocalURL(for: videoUrl),
               FileManager.default.fileExists(atPath: localURL.path) {
                DispatchQueue.global(qos: .userInteractive).async {
                    AppInstance.instance.generateThumbnail(from: localURL, completion: { image in
                        DispatchQueue.main.async {
                            if let image = image {
                                cell.videoImageView.image = image
                            } else {
                                cell.videoImageView.image = UIImage(named: "")
                            }
                        }
                    })
                }
                cell.blurView.isHidden = true // Hide download button
            } else {
                DispatchQueue.global(qos: .userInteractive).async {
                    AppInstance.instance.generateThumbnail(from: videoUrl, completion: { image in
                        DispatchQueue.main.async {
                            if let image = image {
                                cell.videoImageView.image = image
                            } else {
                                cell.videoImageView.image = UIImage(named: "")
                            }
                        }
                    })
                }
            }
        } else {
            cell.blurView.isHidden = true
            DispatchQueue.global(qos: .userInteractive).async {
                AppInstance.instance.generateThumbnail(from: videoUrl, completion: { image in
                    DispatchQueue.main.async {
                        if let image = image {
                            cell.videoImageView.image = image
                        } else {
                            cell.videoImageView.image = UIImage(named: "")
                        }
                    }
                })
            }
        }
        cell.messageVideoButton.tag = indexPathForCell.row
        cell.messageVideoButton.addTarget(self, action: #selector(self.clickVideoButton), for: .touchUpInside)
        if objChatList._reaction == "" {
            cell.reactionImageView.isHidden = true
        } else {
            cell.reactionImageView.isHidden = false
            cell.reactionImageView.image = self.setReactionEmoji(type: objChatList._reaction)
        }
        if objChatList.fav == "on" {
            cell.starImageView.isHidden = false
        } else {
            cell.starImageView.isHidden = true
        }
        if isColor != "" {
            cell.messageView.backgroundColor = UIColor(hex: isColor)
        } else {
            cell.messageView.backgroundColor = UIColor(hex: "#C83747")
        }
        if objChatList.seen == "0" {
            cell.lastSeenImage.image = UIImage(named: "ic_seenCheck")?.withRenderingMode(.alwaysTemplate)
            if isColor != "" {
                cell.lastSeenImage.tintColor = UIColor(hex: isColor)
            } else {
                cell.lastSeenImage.tintColor = UIColor(hex: "C83747")
            }
        } else {
            cell.lastSeenImage.image = UIImage(named: "ic_seen")?.withRenderingMode(.alwaysTemplate)
            if isColor != "" {
                cell.lastSeenImage.tintColor = UIColor(hex: isColor)
            } else {
                cell.lastSeenImage.tintColor = UIColor(hex: "C83747")
            }
        }
    }
    
    // Set Left Gif Data
    private func setLeftGifData(cell: LeftGifTableViewCell, indexPathForCell: IndexPath) {
        cell.swipeRecognizer.isEnabled = false
        let objChatList = self.messagesArray[indexPathForCell.row]
        cell.forwardedView.isHidden = objChatList.forward == "0"
        cell.userStackView.isHidden = true
        cell.replyMessageView.isHidden = true
        cell.replyStoryView.isHidden = true
        cell.messageTimeLabel.text = objChatList.time?.timeStampStringToTime()
        let gifUrl = URL(string: objChatList.stickers ?? "")
        let indicator = SDWebImageActivityIndicator.medium
        cell.videoImageView.sd_imageIndicator = indicator
        DispatchQueue.global(qos: .userInteractive).async {
            cell.videoImageView.sd_setImage(with: gifUrl, placeholderImage: UIImage(named: ""))
        }
        cell.messageGifButton.tag = indexPathForCell.row
        cell.messageGifButton.addTarget(self, action: #selector(self.clickGif), for: .touchUpInside)
        if objChatList._reaction == "" {
            cell.reactionImageView.isHidden = true
        } else {
            cell.reactionImageView.isHidden = false
            cell.reactionImageView.image = self.setReactionEmoji(type: objChatList._reaction)
        }
        if objChatList.fav == "on" {
            cell.starImageView.isHidden = false
        } else {
            cell.starImageView.isHidden = true
        }
        // cell.messageView.backgroundColor = UIColor(hex: "#F2F2F2")
    }
    
    // Set Right Gif Data
    private func setRightGifData(cell: RightGifTableViewCell, indexPathForCell: IndexPath) {
        cell.swipeRecognizer.isEnabled = false
        let objChatList = self.messagesArray[indexPathForCell.row]
        cell.forwardedView.isHidden = objChatList.forward == "0"
        cell.replyMessageView.isHidden = true
        cell.replyStoryView.isHidden = true
        cell.messageTimeLabel.text = objChatList.time?.timeStampStringToTime()
        let gifUrl = URL(string: objChatList.stickers ?? "")
        let indicator = SDWebImageActivityIndicator.medium
        cell.videoImageView.sd_imageIndicator = indicator
        DispatchQueue.global(qos: .userInteractive).async {
            cell.videoImageView.sd_setImage(with: gifUrl, placeholderImage: UIImage(named: ""))
        }
        cell.messageGifButton.tag = indexPathForCell.row
        cell.messageGifButton.addTarget(self, action: #selector(self.clickGif), for: .touchUpInside)
        if objChatList._reaction == "" {
            cell.reactionImageView.isHidden = true
        } else {
            cell.reactionImageView.isHidden = false
            cell.reactionImageView.image = self.setReactionEmoji(type: objChatList._reaction)
        }
        if objChatList.fav == "on" {
            cell.starImageView.isHidden = false
        } else {
            cell.starImageView.isHidden = true
        }
        if isColor != "" {
            cell.messageView.backgroundColor = UIColor(hex: isColor)
        } else {
            cell.messageView.backgroundColor = UIColor(hex: "C83747")
        }
        if objChatList.seen == "0" {
            cell.lastSeenImage.image = UIImage(named: "ic_seenCheck")?.withRenderingMode(.alwaysTemplate)
            if isColor != "" {
                cell.lastSeenImage.tintColor = UIColor(hex: isColor)
            } else {
                cell.lastSeenImage.tintColor = UIColor(hex: "C83747")
            }
        } else {
            cell.lastSeenImage.image = UIImage(named: "ic_seen")?.withRenderingMode(.alwaysTemplate)
            if isColor != "" {
                cell.lastSeenImage.tintColor = UIColor(hex: isColor)
            } else {
                cell.lastSeenImage.tintColor = UIColor(hex: "C83747")
            }
        }
    }
    
    // Set Left Contact Data
    private func setLeftContactData(cell: LeftContactTableViewCell,  indexpathForCell: IndexPath) {
        cell.swipeRecognizer.isEnabled = false
        let objChatList = self.messagesArray[indexpathForCell.row]
        cell.forwardedView.isHidden = objChatList.forward == "0"
        cell.userStackView.isHidden = true
        cell.replyMessageView.isHidden = true
        cell.replyStoryView.isHidden = true
        let phoneData = htmlToString(text: objChatList.text ?? "")
        let contactName = phoneData?["Key"] as? String ?? ""
        let phoneNumber = phoneData?["Value"] as? String ?? ""
        if contactName != "" {
            cell.contactNameLabel.text = "\(contactName)"
        } else if phoneNumber != "" {
            cell.contactNameLabel.text = "\(phoneNumber)"
        }
        cell.messageTimeLabel.text = objChatList.time?.timeStampStringToTime()
        cell.contactButton.tag = indexpathForCell.row
        cell.contactButton.addTarget(self, action: #selector(self.openContact), for: .touchUpInside)
        if objChatList._reaction == "" {
            cell.reactionImageView.isHidden = true
        } else {
            cell.reactionImageView.isHidden = false
            cell.reactionImageView.image = self.setReactionEmoji(type: objChatList._reaction)
        }
        if objChatList.fav == "on" {
            cell.starImageView.isHidden = false
        } else {
            cell.starImageView.isHidden = true
        }
        // cell.messageView.backgroundColor = UIColor(hex: "#F2F2F2")
        if isColor != "" {
            cell.contactImageView.tintColor = UIColor(hex: isColor)
        } else {
            cell.contactImageView.tintColor = UIColor(hex: "C83747")
        }
    }
    
    // Set Right Contact Data
    private func setRightContactData(cell: RightContactTableViewCell,  indexpathForCell: IndexPath) {
        cell.swipeRecognizer.isEnabled = false
        let objChatList = self.messagesArray[indexpathForCell.row]
        cell.forwardedView.isHidden = objChatList.forward == "0"
        cell.replyMessageView.isHidden = true
        cell.replyStoryView.isHidden = true
        let phoneData = htmlToString(text: objChatList.text ?? "")
        let contactName = phoneData?["Key"] as? String ?? ""
        let phoneNumber = phoneData?["Value"] as? String ?? ""
        if contactName != "" {
            cell.contactNameLabel.text = "\(contactName)"
        } else if phoneNumber != "" {
            cell.contactNameLabel.text = "\(phoneNumber)"
        }
        cell.messageTimeLabel.text = objChatList.time?.timeStampStringToTime()
        cell.contactButton.tag = indexpathForCell.row
        cell.contactButton.addTarget(self, action: #selector(self.openContact), for: .touchUpInside)
        if objChatList._reaction == "" {
            cell.reactionImageView.isHidden = true
        } else {
            cell.reactionImageView.isHidden = false
            cell.reactionImageView.image = self.setReactionEmoji(type: objChatList._reaction)
        }
        if objChatList.fav == "on" {
            cell.starImageView.isHidden = false
        } else {
            cell.starImageView.isHidden = true
        }
        if isColor != "" {
            cell.messageView.backgroundColor = UIColor(hex: isColor)
        } else {
            cell.messageView.backgroundColor = UIColor(hex: "C83747")
        }
        if objChatList.seen == "0" {
            cell.lastSeenImage.image = UIImage(named: "ic_seenCheck")?.withRenderingMode(.alwaysTemplate)
            if isColor != "" {
                cell.lastSeenImage.tintColor = UIColor(hex: isColor)
            } else {
                cell.lastSeenImage.tintColor = UIColor(hex: "C83747")
            }
        } else {
            cell.lastSeenImage.image = UIImage(named: "ic_seen")?.withRenderingMode(.alwaysTemplate)
            if isColor != "" {
                cell.lastSeenImage.tintColor = UIColor(hex: isColor)
            } else {
                cell.lastSeenImage.tintColor = UIColor(hex: "C83747")
            }
        }
    }
    
    // Set Left Document Data
    private func setLeftDocumentData(cell: LeftDocumentTableViewCell, indexPathForCell: IndexPath) {
        cell.swipeRecognizer.isEnabled = false
        let objChatList = self.messagesArray[indexPathForCell.row]
        cell.forwardedView.isHidden = objChatList.forward == "0"
        cell.userStackView.isHidden = true
        cell.replyMessageView.isHidden = true
        cell.replyStoryView.isHidden = true
        let fileURL = URL(string: objChatList.media ?? "")
        cell.messageTimeLabel.text = objChatList.time?.timeStampStringToTime()
        cell.fileNameLabel.text = fileURL?.lastPathComponent ?? ""
        cell.fileSizeLabel.text = objChatList.file_size?.stringValue
        cell.fileMessageButton.tag = indexPathForCell.row
        cell.fileMessageButton.addTarget(self, action: #selector(self.clickFile), for: .touchUpInside)
        if objChatList._reaction == "" {
            cell.reactionImageView.isHidden = true
        } else {
            cell.reactionImageView.isHidden = false
            cell.reactionImageView.image = self.setReactionEmoji(type: objChatList._reaction)
        }
        if objChatList.fav == "on" {
            cell.starImageView.isHidden = false
        } else {
            cell.starImageView.isHidden = true
        }
        // cell.messageView.backgroundColor = UIColor(hex: "#F2F2F2")
        if isColor != "" {
            cell.fileButton.backgroundColor = UIColor(hex: isColor)
        } else {
            cell.fileButton.backgroundColor = UIColor(hex: "C83747")
        }
    }
    
    // Set Right Document Data
    private func setRightDocumentData(cell: RightDocumentTableViewCell, indexPathForCell: IndexPath) {
        cell.swipeRecognizer.isEnabled = false
        let objChatList = self.messagesArray[indexPathForCell.row]
        cell.forwardedView.isHidden = objChatList.forward == "0"
        cell.replyMessageView.isHidden = true
        cell.replyStoryView.isHidden = true
        let fileURL = URL(string: objChatList.media ?? "")
        cell.messageTimeLabel.text = objChatList.time?.timeStampStringToTime()
        cell.fileNameLabel.text = fileURL?.lastPathComponent ?? ""
        cell.fileSizeLabel.text = objChatList.file_size?.stringValue
        cell.fileMessageButton.tag = indexPathForCell.row
        cell.fileMessageButton.addTarget(self, action: #selector(self.clickFile), for: .touchUpInside)
        if objChatList._reaction == "" {
            cell.reactionImageView.isHidden = true
        } else {
            cell.reactionImageView.isHidden = false
            cell.reactionImageView.image = self.setReactionEmoji(type: objChatList._reaction)
        }
        if objChatList.fav == "on" {
            cell.starImageView.isHidden = false
        } else {
            cell.starImageView.isHidden = true
        }
        if isColor != "" {
            cell.messageView.backgroundColor = UIColor(hex: isColor)
            cell.fileImageView.tintColor = UIColor(hex: isColor)
        } else {
            cell.messageView.backgroundColor = UIColor(hex: "C83747")
            cell.fileImageView.tintColor = UIColor(hex: "C83747")
        }
        if objChatList.seen == "0" {
            cell.lastSeenImage.image = UIImage(named: "ic_seenCheck")?.withRenderingMode(.alwaysTemplate)
            if isColor != "" {
                cell.lastSeenImage.tintColor = UIColor(hex: isColor)
            } else {
                cell.lastSeenImage.tintColor = UIColor(hex: "C83747")
            }
        } else {
            cell.lastSeenImage.image = UIImage(named: "ic_seen")?.withRenderingMode(.alwaysTemplate)
            if isColor != "" {
                cell.lastSeenImage.tintColor = UIColor(hex: isColor)
            } else {
                cell.lastSeenImage.tintColor = UIColor(hex: "C83747")
            }
        }
    }
    
    // Set Left Audio Data
    private func setLeftAudioData(cell: LeftAudioTableViewCell, indexPathForCell: IndexPath) {
        cell.swipeRecognizer.isEnabled = false
        let objChatList = messagesArray[indexPathForCell.row]
        cell.forwardedView.isHidden = objChatList.forward == "0"
        cell.userStackView.isHidden = true
        cell.replyMessageView.isHidden = true
        cell.replyStoryView.isHidden = true
        if let audioURL = URL(string: objChatList.media ?? "") {
            cell.playButtonTapHandler = {
                AudioPlayerHelper.shared.playAudio(at: indexPathForCell, url: audioURL)
            }
            cell.setupAudioPlayer(url: audioURL, indexPath: indexPathForCell)
        }
        cell.messageTimeLabel.text = objChatList.time?.timeStampStringToTime()
        if objChatList._reaction == "" {
            cell.reactionImageView.isHidden = true
        } else {
            cell.reactionImageView.isHidden = false
            cell.reactionImageView.image = self.setReactionEmoji(type: objChatList._reaction)
        }
        if objChatList.fav == "on" {
            cell.starImageView.isHidden = false
        } else {
            cell.starImageView.isHidden = true
        }
        // cell.messageView.backgroundColor = UIColor(hex: "#F2F2F2")
        if isColor != "" {
            cell.playButton.backgroundColor = UIColor(hex: isColor)
            cell.audioSliderView.minimumTrackTintColor = UIColor(hex: isColor)
            cell.audioSliderView.maximumTrackTintColor = UIColor(hex: isColor).withAlphaComponent(0.34)
            cell.audioSliderView.setThumbImage(UIImage(named: "slider_thumb")?.withTintColor(.init(hex: isColor)), for: .normal)
            cell.audioSliderView.setThumbImage(UIImage(named: "slider_thumb")?.withTintColor(.init(hex: isColor)), for: .highlighted)
        } else {
            cell.playButton.backgroundColor = UIColor(hex: "C83747")
            cell.audioSliderView.minimumTrackTintColor = UIColor(hex: "C83747")
            cell.audioSliderView.maximumTrackTintColor = UIColor(hex: "C83747").withAlphaComponent(0.34)
            cell.audioSliderView.setThumbImage(UIImage(named: "slider_thumb")?.withTintColor(.init(hex: "C83747")), for: .normal)
            cell.audioSliderView.setThumbImage(UIImage(named: "slider_thumb")?.withTintColor(.init(hex: "C83747")), for: .highlighted)
        }
    }
    
    // Set Right Audio Data
    private func setRightAudioData(cell: RightAudioTableViewCell, indexPathForCell: IndexPath) {
        cell.swipeRecognizer.isEnabled = false
        let objChatList = messagesArray[indexPathForCell.row]
        cell.forwardedView.isHidden = objChatList.forward == "0"
        cell.replyMessageView.isHidden = true
        cell.replyStoryView.isHidden = true
        if let audioURL = URL(string: objChatList.media ?? "") {
            cell.playButtonTapHandler = {
                AudioPlayerHelper.shared.playAudio(at: indexPathForCell, url: audioURL)
            }
            cell.setupAudioPlayer(url: audioURL, indexPath: indexPathForCell)
        }
        cell.messageTimeLabel.text = objChatList.time?.timeStampStringToTime()
        if objChatList._reaction == "" {
            cell.reactionImageView.isHidden = true
        } else {
            cell.reactionImageView.isHidden = false
            cell.reactionImageView.image = self.setReactionEmoji(type: objChatList._reaction)
        }
        if objChatList.fav == "on" {
            cell.starImageView.isHidden = false
        } else {
            cell.starImageView.isHidden = true
        }
        if isColor != "" {
            cell.messageView.backgroundColor = UIColor(hex: isColor)
            cell.playButton.tintColor = UIColor(hex: isColor)
        } else {
            cell.messageView.backgroundColor = UIColor(hex: "C83747")
            cell.playButton.tintColor = UIColor(hex: "C83747")
        }
        if objChatList.seen == "0" {
            cell.lastSeenImage.image = UIImage(named: "ic_seenCheck")?.withRenderingMode(.alwaysTemplate)
            if isColor != "" {
                cell.lastSeenImage.tintColor = UIColor(hex: isColor)
            } else {
                cell.lastSeenImage.tintColor = UIColor(hex: "C83747")
            }
        } else {
            cell.lastSeenImage.image = UIImage(named: "ic_seen")?.withRenderingMode(.alwaysTemplate)
            if isColor != "" {
                cell.lastSeenImage.tintColor = UIColor(hex: isColor)
            } else {
                cell.lastSeenImage.tintColor = UIColor(hex: "C83747")
            }
        }
    }
    
    // Set Left Sticker Data
    private func setLeftStickerData(cell: LeftStickerCell, indexPathForCell: IndexPath) {
        cell.swipeRecognizer.isEnabled = false
        let objChatList = self.messagesArray[indexPathForCell.row]
        cell.forwardedView.isHidden = objChatList.forward == "0"
        cell.userStackView.isHidden = true
        cell.replyMessageView.isHidden = true
        cell.replyStoryView.isHidden = true
        let stickerUrl = URL(string: objChatList.media ?? "")
        let indicator = SDWebImageActivityIndicator.medium
        cell.sendImageView.sd_imageIndicator = indicator
        DispatchQueue.global(qos: .userInteractive).async {
            cell.sendImageView.sd_setImage(with: stickerUrl, placeholderImage: UIImage(named: ""))
        }
        cell.messageTimeLabel.text = objChatList.time?.timeStampStringToTime()
        if objChatList._reaction == "" {
            cell.reactionImageView.isHidden = true
        } else {
            cell.reactionImageView.isHidden = false
            cell.reactionImageView.image = self.setReactionEmoji(type: objChatList._reaction)
        }
        if objChatList.fav == "on" {
            cell.starImageView.isHidden = false
        } else {
            cell.starImageView.isHidden = true
        }
    }
    
    // Set Right Sticker Data
    private func setRightStickerData(cell: RightStickerCell, indexPathForCell: IndexPath) {
        cell.swipeRecognizer.isEnabled = false
        let objChatList = self.messagesArray[indexPathForCell.row]
        cell.forwardedView.isHidden = objChatList.forward == "0"
        cell.replyMessageView.isHidden = true
        cell.replyStoryView.isHidden = true
        let stickerUrl = URL(string: objChatList.media ?? "")
        let indicator = SDWebImageActivityIndicator.medium
        cell.sendImageView.sd_imageIndicator = indicator
        DispatchQueue.global(qos: .userInteractive).async {
            cell.sendImageView.sd_setImage(with: stickerUrl, placeholderImage: UIImage(named: ""))
        }
        cell.messageTimeLabel.text = objChatList.time?.timeStampStringToTime()
        if objChatList._reaction == "" {
            cell.reactionImageView.isHidden = true
        } else {
            cell.reactionImageView.isHidden = false
            cell.reactionImageView.image = self.setReactionEmoji(type: objChatList._reaction)
        }
        if objChatList.fav == "on" {
            cell.starImageView.isHidden = false
        } else {
            cell.starImageView.isHidden = true
        }
        if objChatList.seen == "0" {
            cell.lastSeenImage.image = UIImage(named: "ic_seenCheck")?.withRenderingMode(.alwaysTemplate)
            if isColor != "" {
                cell.lastSeenImage.tintColor = UIColor(hex: isColor)
            } else {
                cell.lastSeenImage.tintColor = UIColor(hex: "C83747")
            }
        } else {
            cell.lastSeenImage.image = UIImage(named: "ic_seen")?.withRenderingMode(.alwaysTemplate)
            if isColor != "" {
                cell.lastSeenImage.tintColor = UIColor(hex: isColor)
            } else {
                cell.lastSeenImage.tintColor = UIColor(hex: "C83747")
            }
        }
    }
    
    // click Video Button
    @objc func clickVideoButton(_ sender: UIButton) {
        let object = self.messagesArray[sender.tag]
        let player = AVPlayer(url: URL(string: object.media ?? "")!)
        let vc = AVPlayerViewController()
        vc.player = player
        self.present(vc, animated: true) {
            vc.player?.play()
        }
    }
    
    // Click Image Click
    @objc func clickImageClick(_ sender: UIButton) {
        let object = self.messagesArray[sender.tag]
        let vc = R.storyboard.dashboard.showImageVC()
        vc?.imageURL = object.media ?? ""
        vc?.isGif = false
        vc?.modalPresentationStyle = .fullScreen
        vc?.modalTransitionStyle = .coverVertical
        self.present(vc!, animated: true, completion: nil)
    }
    
    // Open Contact
    @objc func openContact(_ sender: UIButton) {
        let object = self.messagesArray[sender.tag]
        let phoneData = htmlToString(text: object.text ?? "")
        let contact = CNMutableContact()
        contact.givenName = phoneData?["Key"] as? String ?? ""
        contact.phoneNumbers = [CNLabeledValue(label: CNLabelHome, value: CNPhoneNumber(stringValue: phoneData?["Value"] as? String ?? ""))]
        let contactViewController = CNContactViewController(forNewContact: contact)
        contactViewController.delegate = self
        let navigationController = UINavigationController(rootViewController: contactViewController)
        present(navigationController, animated: true, completion: nil)
    }
    
    @objc func setLocationNavigaction(_ sender: UIButton) {
        let object = self.messagesArray[sender.tag]
        guard let url = URL(string: "comgooglemaps://") else {
            return
        }
        if UIApplication.shared.canOpenURL(url) {
            let url = URL(string: "comgooglemaps://?saddr=&daddr=\(object.lng ?? ""),\(object.lng ?? "")&directionsmode=driving")
            UIApplication.shared.open(url!, options: [:], completionHandler: nil)
        } else {
            let regionDistance: CLLocationDistance = 10000
            let coordinates = CLLocationCoordinate2DMake(Double(object.lat ?? "") ?? 0, Double(object.lng ?? "") ?? 0)
            let regionSpan = MKCoordinateRegion(center: coordinates, latitudinalMeters: regionDistance, longitudinalMeters: regionDistance)
            var options = NSObject()
            options = [
                MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: regionSpan.center),
                MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: regionSpan.span),
                MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving
            ] as NSObject
            let placemark = MKPlacemark(coordinate: coordinates, addressDictionary: nil)
            let mapItem = MKMapItem(placemark: placemark)
            mapItem.openInMaps(launchOptions: options as? [String: AnyObject])
        }
    }
    
    // Click File
    @objc func clickFile(_ sender: UIButton) {
        let object = self.messagesArray[sender.tag]
        if let pdfURL = URL(string: object.media ?? "") {
            let safariViewController = SFSafariViewController(url: pdfURL)
            safariViewController.delegate = self
            present(safariViewController, animated: true, completion: nil)
        }
    }
    
    @objc func clickGif(_ sender: UIButton) {
        let object = self.messagesArray[sender.tag]
        let vc = R.storyboard.dashboard.showImageVC()
        vc?.imageURL = object.stickers ?? ""
        vc?.isGif = true
        vc?.modalPresentationStyle = .fullScreen
        vc?.modalTransitionStyle = .coverVertical
        self.present(vc!, animated: true, completion: nil)
    }
    
}

// MARK: AudioPlayerDelegate Methods
extension PinnedAndFavouriteMessageVC: AudioPlayerDelegate {
    
    func playbackStateChanged(at indexPath: IndexPath?) {
        if let indexPath = indexPath {
            self.tableView.reloadRows(at: [indexPath], with: .none)
        }
    }
    
}

// MARK: CNContactViewControllerDelegate Methods
extension PinnedAndFavouriteMessageVC: CNContactViewControllerDelegate {
    
    func contactViewController(_ viewController: CNContactViewController, didCompleteWith contact: CNContact?) {
        dismiss(animated: true, completion: nil)
        if contact != nil {
            print("Contact saved successfully!")
        } else {
            print("Contact creation cancelled or failed.")
        }
    }
    
}

// MARK: SFSafariViewControllerDelegate Methods
extension PinnedAndFavouriteMessageVC: SFSafariViewControllerDelegate {
    
    func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
        controller.dismiss(animated: true, completion: nil)
    }
    
}

// MARK: PinnedMessageOptionVCDelegate
extension PinnedAndFavouriteMessageVC: PinnedAndFavouriteMessageOptionVCDelegate {
    
    func handleMessageOptionTap(index: Int, optionName: String, indexPath: IndexPath) {
        let object = self.messagesArray[indexPath.row]
        if index == 0 {
            let messageString = object.orginal_text
            UIPasteboard.general.string = messageString
        } else if index == 1 {
            if let newVC = R.storyboard.favorite.messageInfoViewController() {
                if let message = Messages.getMessageByID(object.id ?? "") {
                    newVC.object = message
                }
                self.navigationController?.pushViewController(newVC, animated: true)
            }
        } else if index == 2 {
            self.deleteMessage(messageID: object.id ?? "", indexPath: indexPath.row)
        } else if index == 3 {
            if let newVC = R.storyboard.favorite.getFriendVC() {
                if let message = Messages.getMessageByID(object.id ?? "") {
                    newVC.message = message
                }
                self.navigationController?.pushViewController(newVC, animated: true)
            }
        } else if index == 4 {
            if let chat_id = self.chatModel?.chat_id {
                if object.pin == "no" {
                    self.pinMessageApi(message_id: object.id ?? "", pin: "yes", chat_id: chat_id)
                } else {
                    self.pinMessageApi(message_id: object.id ?? "", pin: "no", chat_id: chat_id)
                }
            }
            print("pin >>>>> ", object.pin ?? "")
        } else if index == 5 {
            if let chat_id = self.chatModel?.chat_id {
                if object.fav == "no" {
                    self.favMessageApi(message_id: object.id ?? "", fav: "yes", chat_id: chat_id)
                } else {
                    self.favMessageApi(message_id: object.id ?? "", fav: "no", chat_id: chat_id)
                }
            }
            print("fav >>>>> ", object.fav ?? "")
        }
    }
    
}
