//
//  StoryReplyVC.swift
//  WoWonder
//
//  Created by iMac on 20/09/23.
//  Copyright © 2023 ScriptSun. All rights reserved.
//

import UIKit
import AVFAudio
import Async
import Toast_Swift
import AVFoundation
import SDWebImage
import ContactsUI
import MediaPlayer

protocol StoryReplyVCDelegate {
    func handleDismissStoryReplyVC(cell: StoryCell)
}

class StoryReplyVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var bottomView: UIView!
    @IBOutlet weak var replyMessageView: UIView!
    @IBOutlet weak var replyBorderView: UIView!
    @IBOutlet weak var replyUserNameLabel: UILabel!
    @IBOutlet weak var replyMessageLabel: UILabel!
    @IBOutlet weak var replyImageView: UIImageView!
    @IBOutlet weak var replyCancelButton: UIButton!
    @IBOutlet weak var sendMessageView: UIView!
    @IBOutlet weak var audioRecordView: RecordView!
    @IBOutlet weak var sendView: UIView!
    @IBOutlet weak var attachmentButton: UIButton!
    @IBOutlet weak var messageTextView: EmojiTextView!
    @IBOutlet weak var audioRecordButton: RecordButton!
    @IBOutlet weak var sendButton: UIButton!
    @IBOutlet weak var audioRecordSendView: UIView!
    @IBOutlet weak var audioRecordSliderView: UISlider!
    @IBOutlet weak var audioRecordPlayButton: UIButton!
    @IBOutlet weak var audioRecordDeleteButton: UIButton!
    @IBOutlet weak var audioRecordSendButton: UIButton!
    @IBOutlet weak var audioRecordSendViewHeight: NSLayoutConstraint!
    
    // MARK: - Properties
    
    var delegate: StoryReplyVCDelegate?
    var audioRecorderHelper: AudioRecorderHelper!
    var audioFileURL: URL?
    var audioRecoderPlayer : AVAudioPlayer!
    var isSendRecordAudio = false
    var audioRecodeTimer: Timer?
    private var toneStatus = false
    private var sendMessageAudioPlayer: AVAudioPlayer?
    var story: UserDataStory?
    var cell = StoryCell()
    var imagePickerMediaType: ImagePickerMediaType = .IMAGE
    private var imagePicker = UIImagePickerController()
    
    // MARK: - View Life Cycles

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        self.initialConfig()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        self.audioRecoderPlayer?.pause()
        self.audioRecodeTimer?.invalidate()
        self.audioRecodeTimer = nil
        self.audioRecordPlayButton.setImage(UIImage(named: "icon_play_vector"), for: .normal)
    }
    
    // MARK: - Selectors
    
    // Attachment Button Action
    @IBAction func attachmentButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.popup.attachmentAlertVC() {
            newVC.delegate = self
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            self.present(newVC, animated: true)
        }
    }
    
    // Send Button Action
    @IBAction func sendButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if messageTextView.text != "" {
            self.sendMessage(text: messageTextView.text, lat: 0, lng: 0)
        }
    }
    
    // Emoji Button Action
    @IBAction func emojiButtonAction(_ sender: UIButton) {
        self.messageTextView.isEmojiKeyboard = true
        self.messageTextView.becomeFirstResponder()
    }
    
    // Audio Record Play Button Action
    @IBAction func audioRecordPlayButtonAction(_ sender: UIButton) {
        if self.audioRecoderPlayer.isPlaying {
            self.audioRecoderPlayer?.pause()
            self.audioRecodeTimer?.invalidate()
            self.audioRecodeTimer = nil
            self.audioRecordPlayButton.setImage(UIImage(named: "icon_play_vector"), for: .normal)
        } else {
            self.audioRecoderPlayer?.play()
            self.audioRecodeTimer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(self.updatePlaybackProgress), userInfo: nil, repeats: true)
            self.audioRecordPlayButton.setImage(UIImage(named: "icon_pause_vector"), for: .normal)
        }
    }
    
    @IBAction func audioRecordSliderValueChanged(_ sender: UISlider) {
        self.audioRecoderPlayer?.currentTime = TimeInterval(sender.value)
    }
    
    @objc func updatePlaybackProgress() {
        self.audioRecordSliderView.value = Float(self.audioRecoderPlayer.currentTime)
    }
    
    // Audio Record Delete Button Action
    @IBAction func audioRecordDeleteButtonAction(_ sender: UIButton) {
        self.hideAudioRecordView()
    }
    
    // Audio Record Send Button Action
    @IBAction func audioRecordSendButtonAction(_ sender: UIButton) {
        if self.isSendRecordAudio {
            if let audioFileURL = self.audioFileURL {
                let audioData = try? Data(contentsOf: audioFileURL)
                self.sendSelectedData(audioData: audioData, imageData: nil, videoData: nil, imageMimeType: nil, VideoMimeType: nil, audioMimeType: audioData?.mimeType, Type: "audio", fileData: nil, fileExtension: nil, FileMimeType: nil)
            }
        }
        self.isSendRecordAudio = false
        self.hideAudioRecordView()
    }
    
    // Cancel Reply Button Action
    @IBAction func cancelReplyButtonAction(_ sender: UIButton) {
        self.dismiss(animated: true) {
            self.delegate?.handleDismissStoryReplyVC(cell: self.cell)
        }
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.setupUI()
        self.setData()
    }
    
    // Set Data
    func setData() {
        self.replyUserNameLabel.text = self.story?.user_data?.name
        if self.story?.videos?.isEmpty ?? false {
            self.replyMessageLabel.text = "Image"
            let imageUrl = URL(string: self.story?.thumbnail ?? "")
            let indicator = SDWebImageActivityIndicator.medium
            self.replyImageView.sd_imageIndicator = indicator
            DispatchQueue.global(qos: .userInteractive).async {
                self.replyImageView.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: ""))
            }
        } else {
            self.replyMessageLabel.text = "Video"
            if let videoURL = URL(string: self.story?.videos?.get(at: 0)?.filename ?? "") {
                self.replyImageView.image = UIImage(named: "")
                self.generateThumbnail(from: videoURL, completion: { image in
                    self.replyImageView.image = image
                })
            }
        }
    }
    
    // Setup UI
    func setupUI() {
        self.view.backgroundColor = .black.withAlphaComponent(0.4)
        self.bottomView.roundCorners(corners: [.topRight, .bottomLeft, .bottomRight], radius: 12)
        self.setUpMessageTextView()
        self.setUpAudioRecordView()
    }
    
    // SetUp Message TextView
    func setUpMessageTextView() {
        self.messageTextView.delegate = self
        self.messageTextView.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        self.messageTextView.addPlaceholder("Write your message", with: UIColor.text_color_in_between)
        self.setSendButton()
    }
    
    // Set Send Button
    func setSendButton() {
        if self.messageTextView.text == "" {
            self.sendButton.isHidden = true
            self.audioRecordButton.isHidden = false
        } else {
            self.sendButton.isHidden = false
            self.audioRecordButton.isHidden = true
        }
    }
    
    // SetUp Audio Record View
    func setUpAudioRecordView() {
        self.audioRecordView.durationTimerColor = .red
        self.audioRecordButton.recordView = self.audioRecordView
        self.audioRecordView.delegate = self
        self.audioRecordView.isHidden = true
        self.audioRecordSendView.isHidden = true
        self.audioRecordSendViewHeight.constant = 0
        self.audioRecorderHelper = AudioRecorderHelper()
        self.audioRecorderHelper.delegate = self
    }
    
    private func playSendMessageSound() {
        guard let url = Bundle.main.url(forResource: "Popup_SendMesseges", withExtension: "mp3") else { return }
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
            try AVAudioSession.sharedInstance().setActive(true)
            self.sendMessageAudioPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
            self.sendMessageAudioPlayer = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
            guard let aPlayer = sendMessageAudioPlayer else { return }
            aPlayer.play()
            
        } catch let error {
            print(error.localizedDescription)
        }
    }

}

// MARK: - Extensions

// MARK: Api Call
extension StoryReplyVC {
    
    func sendMessage(text: String, lat: Double, lng: Double) {
        let sessionToken = AppInstance.instance._sessionId
        ChatManager.instance.sendMessage(message: text, session_token: sessionToken, ReceipientId: self.story?.user_id?.stringValue ?? "", lat: lat, lng: lng, reply_id: "", story_id: self.story?.id?.stringValue ?? "") { Success, AuthError, ServerKeyError, error in
            if Success != nil {
                Async.main {
                    self.dismissProgressDialog {
                        self.view.resignFirstResponder()
                        if self.toneStatus {
                            self.playSendMessageSound()
                        } else {
                            
                        }
                        self.messageTextView.text = ""
                        self.setSendButton()
                        self.dismiss(animated: true) {
                            self.delegate?.handleDismissStoryReplyVC(cell: self.cell)
                        }
                    }
                }
            } else if AuthError != nil {
                Async.main {
                    self.dismissProgressDialog {
                        self.view.makeToast(AuthError?.errors?.error_text)
                    }
                }
            } else if ServerKeyError != nil {
                Async.main {
                    self.dismissProgressDialog {
                        self.view.makeToast(ServerKeyError?.errors?.error_text)
                    }
                }
            } else {
                Async.main {
                    self.dismissProgressDialog {
                        self.view.makeToast(error?.localizedDescription)
                    }
                }
            }
        }
    }
    
    private func sendSelectedData(audioData: Data?, imageData: Data?, videoData: Data?, imageMimeType: String?, VideoMimeType: String?, audioMimeType: String?, Type: String?, fileData: Data?, fileExtension: String?, FileMimeType: String?) {
        let messageHashId = Int(arc4random_uniform(UInt32(100000)))
        let sessionId = AppInstance.instance._sessionId
        let dataType = Type ?? ""
        if dataType == "image" {
            Async.background {
                ChatManager.instance.sendChatData(message_hash_id: messageHashId, receipent_id: self.story?.user_id?.stringValue ?? "", session_Token: sessionId, type: dataType, audio_data: nil, image_data: imageData, video_data: nil, imageMimeType: imageMimeType, videoMimeType: nil, audioMimeType: nil, text: "", file_data: nil, file_Extension: nil, fileMimeType: nil, reply_id: "", story_id: self.story?.id?.stringValue ?? "") { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.resignFirstResponder()
                                self.dismiss(animated: true) {
                                    self.delegate?.handleDismissStoryReplyVC(cell: self.cell)
                                }
                            }
                        }
                    } 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)
                            }
                        }
                    }
                }
            }
        }
        if dataType == "audio" {
            Async.background {
                ChatManager.instance.sendChatData(message_hash_id: messageHashId, receipent_id: self.story?.user_id?.stringValue ?? "", session_Token: sessionId, type: dataType, audio_data: audioData, image_data: nil, video_data: nil, imageMimeType: nil, videoMimeType: nil,audioMimeType: audioMimeType, text: "", file_data: nil, file_Extension: "mp3", fileMimeType: nil, reply_id: "", story_id: self.story?.id?.stringValue ?? "") { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.resignFirstResponder()
                                self.dismiss(animated: true) {
                                    self.delegate?.handleDismissStoryReplyVC(cell: self.cell)
                                }
                            }
                        }
                    } else if sessionError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(sessionError?.errors?.error_text)
                                print("sessionError = \(sessionError?.errors?.error_text ?? "")")
                            }
                        }
                    } else if serverError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(serverError?.errors?.error_text)
                                print("serverError = \(serverError?.errors?.error_text ?? "")")
                            }
                        }
                    } else {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.makeToast(error?.localizedDescription)
                                print("error = \(error?.localizedDescription ?? "")")
                            }
                        }
                    }
                }
            }
        }
        if dataType == "video" {
            Async.background {
                ChatManager.instance.sendChatData(message_hash_id: messageHashId, receipent_id: self.story?.user_id?.stringValue ?? "", session_Token: sessionId, type: dataType, audio_data: nil, image_data: nil, video_data: videoData, imageMimeType: nil, videoMimeType: VideoMimeType, audioMimeType: nil, text: "", file_data: nil, file_Extension: nil, fileMimeType: nil, reply_id: "", story_id: self.story?.id?.stringValue ?? "") { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.resignFirstResponder()
                                self.dismiss(animated: true) {
                                    self.delegate?.handleDismissStoryReplyVC(cell: self.cell)
                                }
                            }
                        }
                    } 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)
                            }
                        }
                    }
                }
            }
        }
        if dataType == "file" {
            Async.background {
                ChatManager.instance.sendChatData(message_hash_id: messageHashId, receipent_id: self.story?.user_id?.stringValue ?? "", session_Token: sessionId, type: dataType, audio_data: nil, image_data: nil, video_data: nil, imageMimeType: nil, videoMimeType: nil, audioMimeType: nil, text: "", file_data: fileData, file_Extension: fileExtension, fileMimeType: FileMimeType, reply_id: "", story_id: self.story?.id?.stringValue ?? "") { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                self.view.resignFirstResponder()
                                self.dismiss(animated: true) {
                                    self.delegate?.handleDismissStoryReplyVC(cell: self.cell)
                                }
                            }
                        }
                    } 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)
                            }
                        }
                    }
                }
            }
        }
    }
    
    private func sendGIF(url: String) {
        let messageHashId = Int(arc4random_uniform(UInt32(100000)))
        let sessionID = AppInstance.instance._sessionId
        Async.background {
            ChatManager.instance.sendGIF(message_hash_id: messageHashId, receipent_id: self.story?.user_id?.stringValue ?? "", URl: url , session_Token: sessionID, reply_id: "", story_id: self.story?.id?.stringValue ?? "") { (success, sessionError, serverError, error) in
                if success != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            self.view.resignFirstResponder()
                            self.dismiss(animated: true) {
                                self.delegate?.handleDismissStoryReplyVC(cell: self.cell)
                            }
                        }
                    }
                } 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)
                        }
                    }
                }
            }
        }
    }
    
    private func sendContact(jsonPayload: String?) {
        let messageHashId = Int(arc4random_uniform(UInt32(100000)))
        ChatManager.instance.sendContactApiCall(message_hash_id: messageHashId, receipent_id: self.story?.user_id?.stringValue ?? "", sendType: "send", jsonPayload: jsonPayload ?? "", session_Token: AppInstance.instance.sessionId ?? "", reply_id: "", story_id: self.story?.id?.stringValue ?? "") { (success, sessionError, serverError, error) in
            if success != nil {
                Async.main {
                    self.dismissProgressDialog {
                        self.view.resignFirstResponder()
                        self.dismiss(animated: true) {
                            self.delegate?.handleDismissStoryReplyVC(cell: self.cell)
                        }
                    }
                }
            } 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: UITextViewDelegate Methods
extension StoryReplyVC: UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
        self.setSendButton()
    }
    
    func textViewDidEndEditing(_ textView: UITextView) {
        self.messageTextView.isEmojiKeyboard = false
    }
    
}

// MARK: RecordViewDelegate Methods
extension StoryReplyVC: RecordViewDelegate {
    
    func onStart() {
        print("onStart")
        self.audioRecorderHelper.startRecording()
        self.audioRecordView.isHidden = false
        self.audioRecordButton.isHidden = true
        self.attachmentButton.isHidden = true
        self.sendView.isHidden = true
    }
    
    func onCancel() {
        print("onCancel")
        self.audioRecordView.isHidden = true
        self.audioRecordButton.isHidden = false
        self.attachmentButton.isHidden = false
        self.sendView.isHidden = false
        self.isSendRecordAudio = false
        self.audioRecorderHelper.cancelRecording()
    }
    
    func onFinished(duration: CGFloat) {
        print("onFinished \(duration)")
        self.audioRecordView.isHidden = true
        self.audioRecordButton.isHidden = false
        self.attachmentButton.isHidden = false
        self.sendView.isHidden = false
        self.isSendRecordAudio = true
        self.showAudioRecordView()
        self.audioRecorderHelper.stopRecording()
    }
    
    func showAudioRecordView() {
        self.audioRecordSendView.isHidden = false
        self.audioRecordSendViewHeight.constant = 76
        UIView.animate(withDuration: 0.5) {
            self.view.layoutIfNeeded()
        }
    }
    
    func hideAudioRecordView() {
        self.audioRecoderPlayer?.stop()
        self.audioRecodeTimer?.invalidate()
        self.audioRecodeTimer = nil
        self.audioRecordSliderView.value = 0
        self.audioRecordSendViewHeight.constant = 0
        UIView.animate(withDuration: 0.5, animations: {
            self.view.layoutIfNeeded()
        }) { _ in
            self.audioRecordSendView.isHidden = true
        }
    }
    
}

//MARK: AudioRecorderHelperDelegate Methods
extension StoryReplyVC: AudioRecorderHelperDelegate {
    
    func audioRecordingFinished(success: Bool, audioURL: URL?) {
        self.audioFileURL = audioURL
        if let audioFileURL = self.audioFileURL {
            do {
                self.audioRecoderPlayer = try AVAudioPlayer(contentsOf: audioFileURL)
                self.audioRecoderPlayer.delegate = self
                self.audioRecoderPlayer.prepareToPlay()
                self.audioRecordSliderView.value = 0
                self.audioRecordSliderView.minimumValue = 0
                self.audioRecordSliderView.maximumValue = Float(self.audioRecoderPlayer?.duration ?? 0)
            } catch {
                print("Error initializing audio player: \(error)")
            }
        }
    }
    
}

// MARK: AVAudioPlayerDelegate Methods
extension StoryReplyVC: AVAudioPlayerDelegate {
    
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        self.audioRecoderPlayer?.pause()
        self.audioRecodeTimer?.invalidate()
        self.audioRecordSliderView.value = Float(self.audioRecoderPlayer.currentTime)
        self.audioRecordPlayButton.setImage(UIImage(named: "icon_play_vector"), for: .normal)
    }
    
}

// MARK: AttachmentAlertVCDelegate
extension StoryReplyVC: AttachmentAlertVCDelegate {
    
    func handleImageGalleryTap(_ sender: UIButton) {
        self.imagePickerMediaType = .IMAGE
        self.setupGalleryImagePicker(imagePickerMediaType: self.imagePickerMediaType)
    }
    
    func handleTakePictureFromCameraTap(_ sender: UIButton) {
        self.imagePickerMediaType = .IMAGE
        self.setupCameraImagePicker(imagePickerMediaType: self.imagePickerMediaType)
    }
    
    func handleVideoGalleryTap(_ sender: UIButton) {
        self.imagePickerMediaType = .VIDEO
        self.setupGalleryImagePicker(imagePickerMediaType: self.imagePickerMediaType)
    }
    
    func handleRecordVideoFromCameraTap(_ sender: UIButton) {
        self.imagePickerMediaType = .VIDEO
        self.setupCameraImagePicker(imagePickerMediaType: self.imagePickerMediaType)
    }
    
    func handleDocumentButtonTap() {
        self.view.endEditing(true)
        let contentTypes: [UTType] = [
            .init(filenameExtension: "doc")!,
            .init(filenameExtension: "docx")!,
            .pdf,
            .presentation,
            .spreadsheet,
            .plainText,
            .text
        ]
        let pickerController = UIDocumentPickerViewController(forOpeningContentTypes: contentTypes, asCopy: true)
        pickerController.title = "Document"
        pickerController.delegate = self
        pickerController.allowsMultipleSelection = false
        self.present(pickerController, animated: true, completion: nil)
    }
    
    func handleMusicButtonTap() {
        self.view.endEditing(true)
        let contentTypes: [UTType] = [
            .audio
        ]
        let pickerController = UIDocumentPickerViewController(forOpeningContentTypes: contentTypes, asCopy: true)
        pickerController.title = "Audio"
        pickerController.delegate = self
        pickerController.allowsMultipleSelection = false
        self.present(pickerController, animated: true, completion: nil)
    }
    
    func handleGifButtonTap() {
        if let newVC = R.storyboard.chat.gifVC() {
            newVC.delegate = self
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            self.present(newVC, animated: true)
        }
    }
    
    func handleContactButtonTap() {
        let contactPicker = CNContactPickerViewController()
        contactPicker.delegate = self
        contactPicker.displayedPropertyKeys = [CNContactPhoneNumbersKey]
        self.present(contactPicker, animated: true, completion: nil)
    }
    
    func handleLocationButtonTap() {
        if let newVC = R.storyboard.chat.locationVC() {
            newVC.delegate = self
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            self.present(newVC, animated: true)
        }
    }
    
    func setupCameraImagePicker(imagePickerMediaType: ImagePickerMediaType) {
        self.view.endEditing(true)
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            self.imagePicker.delegate = self
            self.imagePicker.sourceType = .camera
            switch imagePickerMediaType {
            case .IMAGE:
                self.imagePicker.mediaTypes = ["public.image"]
            case .VIDEO:
                self.imagePicker.mediaTypes = ["public.movie"]
            }
            self.imagePicker.allowsEditing = false
            self.present(self.imagePicker, animated: true, completion: nil)
        } else {
            if let messageAlertVC = R.storyboard.popup.messageAlertVC() {
                messageAlertVC.messageText = "You don't have camera"
                self.present(messageAlertVC, animated: true, completion: nil)
                messageAlertVC.confirmButton.isHidden = true
            }
        }
    }
    
    func setupGalleryImagePicker(imagePickerMediaType: ImagePickerMediaType) {
        self.view.endEditing(true)
        self.imagePicker.delegate = self
        self.imagePicker.sourceType = .photoLibrary
        switch imagePickerMediaType {
        case .IMAGE:
            self.imagePicker.mediaTypes = ["public.image"]
        case .VIDEO:
            self.imagePicker.mediaTypes = ["public.movie"]
        }
        self.imagePicker.allowsEditing = false
        self.present(self.imagePicker, animated: true, completion: nil)
    }
    
}

// MARK: UIImagePickerControllerDelegate & UINavigationControllerDelegate Methods
extension StoryReplyVC: UIImagePickerControllerDelegate & UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true) {
            switch self.imagePickerMediaType {
            case .IMAGE:
                if let image = info[.originalImage] as? UIImage {
                    let imageData = image.jpegData(compressionQuality: 1)
                    self.sendSelectedData(audioData: nil, imageData: imageData, videoData: nil, imageMimeType: imageData?.mimeType, VideoMimeType: nil, audioMimeType: nil, Type: "image", fileData: nil, fileExtension: nil, FileMimeType: nil)
                }
            case .VIDEO:
                if let videoURL = info[.mediaURL] as? URL {
                    let videoData = try? Data(contentsOf: videoURL)
                    self.sendSelectedData(audioData: nil, imageData: nil, videoData: videoData, imageMimeType: nil, VideoMimeType: videoData?.mimeType, audioMimeType: nil, Type: "video", fileData: nil, fileExtension: nil, FileMimeType: nil)
                }
            }
        }
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
}

// MARK: UIDocumentPickerDelegate Methods
extension StoryReplyVC: UIDocumentPickerDelegate {
    
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
        controller.dismiss(animated: true)
        let fileData = try? Data(contentsOf: url)
        let fileExtension = String(url.lastPathComponent.split(separator: ".").last!)
        switch controller.title {
        case "Document":
            self.sendSelectedData(audioData: nil, imageData: nil, videoData: nil, imageMimeType: nil, VideoMimeType: nil, audioMimeType: nil, Type: "file", fileData: fileData, fileExtension: fileExtension, FileMimeType: fileData?.mimeType)
        case "Audio":
            self.sendSelectedData(audioData: fileData, imageData: nil, videoData: nil, imageMimeType: nil, VideoMimeType: nil, audioMimeType: "application/octet-stream", Type: "audio", fileData: nil, fileExtension: nil, FileMimeType: nil)
        default:
            break
        }
    }
    
    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        print("Cancelled")
    }
    
}

// MARK: DID SELECT GIF
extension StoryReplyVC: didSelectGIFDelegate {
    
    func didSelectGIF(GIFUrl: String, id: String) {
        self.sendGIF(url: GIFUrl)
    }
    
}

// MARK: CNContactPickerDelegate Methods
extension StoryReplyVC: CNContactPickerDelegate {
    
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contactProperty: CNContactProperty) {
        if let phoneNumber = contactProperty.value as? CNPhoneNumber {
            let contactNumber = phoneNumber.stringValue
            let fullName = CNContactFormatter.string(from: contactProperty.contact, style: .fullName)
            let extendedParam = ["Key": fullName, "Value": contactNumber] as? [String: String]
            if let theJSONData = try?  JSONSerialization.data(withJSONObject: extendedParam ?? [:], options: []) {
                let theJSONText = String(data: theJSONData, encoding: String.Encoding.utf8)
                print("JSON string = \(theJSONText ?? "")")
                self.sendContact(jsonPayload: theJSONText)
            }
        }
    }
    
    func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
        // Handle the cancel action
    }
    
}

// MARK: SEND LOCATION PROTOCOL
extension StoryReplyVC: sendLocationProtocol {
    
    func sendLocation(lat: Double, long: Double) {
        self.sendMessage(text: "", lat: lat, lng: long)
    }
    
}
