//
//  UserProfileController.swift
//  WoWonder
//
//  Created by Ubaid Javaid on 7/16/20.
//  Copyright © 2020 ScriptSun. All rights reserved.
//

import UIKit
import WowonderMessengerSDK
import Async
import DropDown
import AVFoundation
import AVKit
import Toast_Swift
import SafariServices
import SDWebImage

class UserProfileViewController: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var headerNameLabel: UILabel!
    @IBOutlet weak var profileImage: UIImageView!
    @IBOutlet weak var qrCodeButton: UIButton!
    @IBOutlet weak var editButton: UIButton!
    @IBOutlet weak var buttonStackView: UIStackView!
    @IBOutlet weak var chatButton: UIButton!
    @IBOutlet weak var followButton: UIButton!
    @IBOutlet weak var userNameLabel: UILabel!
    @IBOutlet weak var userInfoLabel: UILabel!
    @IBOutlet weak var aboutLabel: UILabel!
    @IBOutlet weak var aboutTitleLabel: UILabel!
    @IBOutlet weak var userFollwingLabel: UILabel!
    @IBOutlet weak var userFollowresLabel: UILabel!
    @IBOutlet weak var workView: UIView!
    @IBOutlet weak var wrokLabel: UILabel!
    @IBOutlet weak var schoolView: UIView!
    @IBOutlet weak var schoolLabel: UILabel!
    @IBOutlet weak var addressView: UIView!
    @IBOutlet weak var addressLabel: UILabel!
    @IBOutlet weak var phoneNumberView: UIView!
    @IBOutlet weak var phoneNumberLabel: UILabel!
    @IBOutlet weak var genderView: UIView!
    @IBOutlet weak var genderLabel: UILabel!
    @IBOutlet weak var websiteView: UIView!
    @IBOutlet weak var websiteLabel: UILabel!
    @IBOutlet weak var birthdayView: UIView!
    @IBOutlet weak var birthdayLabel: UILabel!
    @IBOutlet weak var relationshipView: UIView!
    @IBOutlet weak var relationshipLabel: UILabel!
    @IBOutlet weak var mediaView: UIView!
    @IBOutlet weak var viewAllMediaButton: UIButton!
    @IBOutlet weak var mediaCollectionView: UICollectionView!
    @IBOutlet weak var socialLinksView: UIView!
    @IBOutlet weak var facebookView: UIControl!
    @IBOutlet weak var twitterView: UIControl!
    @IBOutlet weak var instagramView: UIControl!
    @IBOutlet weak var vkView: UIControl!
    @IBOutlet weak var youtubeView: UIControl!
    
    // MARK: - Properties
    
    var user_id = ""
    var user_data: UserData?
    var users: Users?
    var admin = ""
    var messageArray: [Messages] = []
    var media: [MessageMedia] = []
    private var player = AVPlayer()
    private let moreDropdown = DropDown()
    var isFromQRCode = false
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initialConfig()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.getUserData(user_ID: self.user_id)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        self.navigationController?.navigationBar.isHidden = true
    }
    
    // MARK: - Selectors
    
    // Back Button Action
    @IBAction func backButtoAction(_ sender: UIButton) {
        if self.isFromQRCode {
            if let viewControllers = self.navigationController?.viewControllers {
                for viewController in viewControllers {
                    if viewController is UserProfileViewController {
                        self.navigationController?.popToViewController(viewController, animated: true)
                        break
                    }
                    if viewController is GroupVC {
                        self.navigationController?.popToViewController(viewController, animated: true)
                        break
                    }
                }
            }
        } else {
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    // Qr Code Button Action
    @IBAction func qrCodeButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.dashboard.qrCodeVC() {
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // More Button Action
    @IBAction func moreButtonAction(_ sender: UIButton) {
        if let newVC = R.storyboard.popup.userProfileMenuAlertVC() {
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            newVC.delegate = self
            newVC.is_blocked = self.user_data?.is_blocked ?? false
            self.navigationController?.present(newVC, animated: true)
            newVC.blockView.isHidden = self.user_id == AppInstance.instance._userId
        }
    }
    
    // Following Button Action
    @IBAction func followingButtonAction(_ sender: UIButton) {
        if let newVC = R.storyboard.dashboard.followingVC() {
            newVC.user_id = self.user_id
            newVC.type = "Following"
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // Followers Button Action
    @IBAction func followersButtonAction(_ sender: UIButton) {
        if let newVC = R.storyboard.dashboard.followingVC() {
            newVC.user_id = self.user_id
            newVC.type = "Followers"
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // Edit Button Action
    @IBAction func editButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.settings.editProfileVC() {
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // Message Button Action
    @IBAction func messageButtonAction(_ sender: UIButton) {
        if !self.chatIsAllowed(user_data: self.user_data) {
            self.view.makeToast("Sorry, chatting with this user is not allowed at this time")
            return
        }
        if let newVC = R.storyboard.chat.chatViewController() {
            newVC.recipientID = self.user_data?.user_id ?? "isFromSettings"
            newVC.userData = self.user_data
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // Follow Button Action
    @IBAction func followButtonAction(_ sender: UIButton) {
        if self.user_data?.is_following == 1 {
            if let messageAlertVC = R.storyboard.popup.messageAlertVC() {
                messageAlertVC.delegate = self
                messageAlertVC.messageText = "Are you sure you want to remove this user as your friend?"
                self.present(messageAlertVC, animated: true, completion: nil)
            }
        } else {
            self.followUser()
        }
    }
    
    // View All Media Button Action
    @IBAction func viewAllMediaButtonAction(_ sender: UIButton) {
        if let newVC = R.storyboard.dashboard.mediaViewController() {
            newVC.media = self.media
            newVC.userId = self.user_data?.user_id ?? ""
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // Facebook Button Action
    @IBAction func facebookButtonAction(_ sender: UIControl) {
        let appURL = URL(string: self.user_data?.facebook ?? "")
        let application = UIApplication.shared
        if application.canOpenURL(appURL ?? URL(fileURLWithPath: "")) {
            application.open(appURL ?? URL(fileURLWithPath: ""))
        } else {
            let webURL = URL(string: self.user_data?.facebook ?? "")
            application.open(webURL!)
        }
    }
    
    // VK Button Action
    @IBAction func vkButtonAction(_ sender: UIControl) {
        let appURL = URL(string: self.user_data?.vk ?? "")
        let application = UIApplication.shared
        if application.canOpenURL(appURL!) {
            application.open(appURL!)
        } else {
            let webURL = URL(string: self.user_data?.vk ?? "")
            application.open(webURL!)
        }
    }
    
    // Instagram Button Action
    @IBAction func instagramButtonAction(_ sender: UIControl) {
        let appURL = URL(string: self.user_data?.instagram ?? "")
        let application = UIApplication.shared
        if application.canOpenURL(appURL!) {
            application.open(appURL!)
        } else {
            let webURL = URL(string: self.user_data?.instagram ?? "")
            application.open(webURL!)
        }
    }
    
    // Youtube Button Action
    @IBAction func youtubeButtonAction(_ sender: UIControl) {
        let appURL = URL(string: self.user_data?.youtube ?? "")
        let application = UIApplication.shared
        if application.canOpenURL(appURL!) {
            application.open(appURL!)
        } else {
            let webURL = URL(string: self.user_data?.youtube ?? "")
            application.open(webURL!)
        }
    }
    
    // Twitter Button Action
    @IBAction func twitterButtonAction(_ sender: UIControl) {
        let appURL = URL(string: self.user_data?.twitter ?? "")
        let application = UIApplication.shared
        if application.canOpenURL(appURL!) {
            application.open(appURL!)
        } else {
            let webURL = URL(string: self.user_data?.twitter ?? "")
            application.open(webURL!)
        }
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.setCurrentUserUI()
        self.setLocalUserData()
        self.setUpMediaView()
    }
    
    // Set Current User UI
    func setCurrentUserUI() {
        if self.user_id == AppInstance.instance._userId {
            self.editButton.isHidden = false
            self.buttonStackView.isHidden = true
            self.qrCodeButton.isHidden = false
        } else {
            self.editButton.isHidden = true
            self.buttonStackView.isHidden = false
            self.qrCodeButton.isHidden = true
        }
    }
    
    // Register Cell
    func setUpMediaView() {
        self.mediaView.isHidden = true
        self.mediaCollectionView.delegate = self
        self.mediaCollectionView.dataSource = self
        self.mediaCollectionView.register(UINib(resource: R.nib.mediaCollectionViewCell), forCellWithReuseIdentifier: R.reuseIdentifier.mediaCollectionViewCell.identifier)
        self.getMessageFromLocal()
    }
    
    func setLocalUserData() {
        self.headerNameLabel.text = "@" + (self.users?.name ?? "")
        let url = URL(string: self.users?.avatar_url ?? "")
        let indicator = SDWebImageActivityIndicator.medium
        self.profileImage.sd_imageIndicator = indicator
        DispatchQueue.global(qos: .userInteractive).async {
            self.profileImage.sd_setImage(with: url, placeholderImage: UIImage(named: ""))
        }
        self.userNameLabel.text = self.users?.name ?? ""
        if self.users?.about == "" || users?.about == nil {
            self.aboutLabel.text = "Hi there i am using WoWonder Messanger"
        } else {
            self.aboutLabel.text = users?.about
        }
    }
    
    private func setData() {
        self.headerNameLabel.text = "@" + (self.user_data?.name ?? "")
        let url = URL(string: self.user_data?.avatar ?? "")
        let indicator = SDWebImageActivityIndicator.medium
        self.profileImage.sd_imageIndicator = indicator
        DispatchQueue.global(qos: .userInteractive).async {
            self.profileImage.sd_setImage(with: url, placeholderImage: UIImage(named: ""))
        }
        self.userFollowresLabel.text = self.user_data?.details?.followers_count?.stringValue
        self.userFollwingLabel.text = self.user_data?.details?.following_count?.stringValue
        self.userNameLabel.text = self.user_data?.name ?? ""
        if self.user_id != AppInstance.instance._userId {
            if self.user_data?.can_follow == 0 && self.user_data?.is_following == 0 {
                self.followButton.isHidden = true
            }
            if user_data?.follow_privacy == "0" {
                self.followButton.isHidden = false
            } else if user_data?.follow_privacy == "1" {
                if (user_data?.is_following_me == 0) {
                    self.followButton.isHidden = user_data?.is_following == 0 ? true : false
                } else if (user_data?.is_following_me == 1) {
                    self.followButton.isHidden = false
                }
            } else {
                self.followButton.isHidden = false
            }
        }
        if self.user_data?.is_following == 0 {
            self.followButton.setTitle("Follow", for: .normal)
            self.followButton.backgroundColor = UIColor.white
            self.followButton.borderWidthV = 1
            self.followButton.borderColorV = UIColor(hex: "#C83747")
            self.followButton.setTitleColor(UIColor(hex: "#C83747"), for: .normal)
        } else {
            self.followButton.setTitle("Following", for: .normal)
            self.followButton.backgroundColor = UIColor(hex: "#C83747")
            self.followButton.setTitleColor(UIColor.white, for: .normal)
        }
        if self.user_data?.about == "" || user_data?.about == nil {
            self.aboutLabel.text = "Hi there i am using WoWonder Messanger"
        } else {
            self.aboutLabel.text = user_data?.about
        }
        if self.user_data?.working == nil || self.user_data?.working == "" {
            self.workView.isHidden = true
        } else {
            self.workView.isHidden = false
            self.wrokLabel.text = user_data?.working
        }
        if self.user_data?.school == nil || self.user_data?.school == "" {
            self.schoolView.isHidden = true
        } else {
            self.schoolView.isHidden = false
            self.schoolLabel.text = user_data?.school
        }
        if self.user_data?.address == nil || self.user_data?.address == "" {
            self.addressView.isHidden = true
        } else {
            self.addressView.isHidden = false
            self.addressLabel.text = user_data?.address
        }
        if self.user_data?.phone_number == nil || self.user_data?.phone_number == "" {
            self.phoneNumberView.isHidden = true
        } else {
            self.phoneNumberView.isHidden = false
            self.phoneNumberLabel.text = user_data?.phone_number
        }
        if self.user_data?.website == nil || self.user_data?.website == "" {
            self.websiteView.isHidden = true
        } else {
            self.websiteView.isHidden = false
            self.websiteLabel.text = user_data?.website
        }
        self.birthdayView.isHidden = true
        if self.user_data?.birthday != nil && self.user_data?.birthday != "" && self.user_data?.birthday != "0000-00-00" {
            if self.user_id != AppInstance.instance._userId {
                if self.user_data?.birth_privacy == "0" {
                    self.birthdayView.isHidden = false
                } else if self.user_data?.birth_privacy == "1" {
                    if self.user_data?.is_following_me == 0 {
                        self.birthdayView.isHidden = self.user_data?.is_following == 0 ? true : false;
                    } else if self.user_data?.is_following_me == 1 {
                        self.birthdayView.isHidden = false
                    }
                }
                self.birthdayLabel.text = user_data?.birthday
            } else {
                self.birthdayView.isHidden = false
                self.birthdayLabel.text = user_data?.birthday
            }
        }
        if self.user_data?.gender == nil || self.user_data?.gender == "" {
            self.genderView.isHidden = true
        } else {
            self.genderView.isHidden = false
            if self.user_data?.gender == "male" {
                self.genderLabel.text = "Male"
            } else {
                self.genderLabel.text = "Female"
            }
        }
        switch self.user_data?.relationship_id {
        case "0":
            self.relationshipLabel.text = "None"
            self.relationshipView.isHidden = false
        case "1":
            self.relationshipLabel.text = "Single"
            self.relationshipView.isHidden = false
        case "2":
            self.relationshipLabel.text = "In a reationship"
            self.relationshipView.isHidden = false
        case "3":
            self.relationshipLabel.text = "Married"
            self.relationshipView.isHidden = false
        case "4":
            self.relationshipLabel.text = "Engaged"
            self.relationshipView.isHidden = false
        default:
            break
        }
        self.setUpSocialLinksView()
    }
    
    func chatIsAllowed(user_data: UserData?) -> Bool {
        if (user_data?.message_privacy == "2") {
            return false
        } else if (user_data?.message_privacy == "1") {
            if (user_data?.is_following == 1) {
                return true
            } else {
                return false
            }
        } else if (user_data?.message_privacy == "0") {
            return true
        }
        return true
    }
    
    // Setup Social Links View
    func setUpSocialLinksView() {
        if (self.user_data?.instagram == nil || self.user_data?.instagram == "") && (self.user_data?.facebook == nil || self.user_data?.facebook == "") && (self.user_data?.youtube == nil || self.user_data?.youtube == "") && (self.user_data?.vk == nil || self.user_data?.vk == "") && (self.user_data?.twitter == nil || self.user_data?.twitter == "") {
            self.socialLinksView.isHidden = true
        } else {
            self.socialLinksView.isHidden = false
        }
        self.instagramView.isHidden = self.user_data?.instagram == nil || self.user_data?.instagram == ""
        self.facebookView.isHidden = self.user_data?.facebook == nil || self.user_data?.facebook == ""
        self.youtubeView.isHidden = self.user_data?.youtube == nil || self.user_data?.youtube == ""
        self.vkView.isHidden = self.user_data?.vk == nil || self.user_data?.vk == ""
        self.twitterView.isHidden = self.user_data?.twitter == nil || self.user_data?.twitter == ""
    }
    
    // Get Message
    func getMessageFromLocal() {
        if self.messageArray.count == 0 {
            if let chat = Chats.getChatByUserID(user_data?.user_id ?? "") {
                let messages = Messages.getMessagesByChatID(chat.chat_id ?? "")
                self.messageArray = messages
            }
        }
        for message in self.messageArray {
            if message.media != "" {
                let media = MessageMedia(media: message.media, type: message.type)
                self.media.append(media)
            } else if message.stickers != "" {
                let media = MessageMedia(media: message.stickers, type: message.type)
                self.media.append(media)
            }
        }
        if self.media.count != 0 {
            self.mediaView.isHidden = false
            self.mediaCollectionView.reloadData()
        }
    }
    
}

// MARK: - Extensions

// MARK: Api call
extension UserProfileViewController {
    
    func followUser() {
        if Connectivity.isConnectedToNetwork() {
            FollowingManager.instance.followRequest(user_Id: user_id, ServerKey: AppInstance.instance._sessionId) { (success, sessionError, serverError, error) in
                if success != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            self.view.makeToast(success?.follow_status ?? "")
                            self.getUserData(user_ID: self.user_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)
                        }
                    }
                }
            }
        } else {
            self.dismissProgressDialog {
                self.view.makeToast(NSLocalizedString("Internet Error", comment: "Internet Error"))
            }
        }
    }
    
    func getUserData(user_ID: String) {
        if Connectivity.isConnectedToNetwork() {
            GetUserDataManager.instance.getUserData(user_id: user_ID, session_Token: AppInstance.instance._sessionId, fetch_type: API.Params.user_data) { (success, sessionError, serverError, error) in
                if success != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            guard let user = success?.user_data else { return }
                            self.user_data = user
                            self.admin = self.user_data?.admin ?? ""
                            self.setData()
                        }
                    }
                } 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)
                        }
                    }
                }
            }
        } else {
            self.dismissProgressDialog {
                self.view.makeToast(NSLocalizedString("Internet Error", comment: "Internet Error"))
            }
        }
    }
    
    private func blockUser(block_action: String) {
        if self.admin == "1" {
            let alert = UIAlertController(title: "", message: NSLocalizedString("You cannot block this user because it is administrator", comment: "You cannot block this user because it is administrator"), preferredStyle: .alert)
            let okay = UIAlertAction(title: NSLocalizedString("Okay", comment: "Okay"), style: .default, handler: nil)
            alert.addAction(okay)
            self.present(alert, animated: true, completion:nil)
        } else {
            Async.background {
                BlockUsersManager.instance.blockUser(user_id: self.user_data?.user_id ?? "", block_action: block_action, completionBlock: { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                print("userList = \(success?.blockStatus ?? "")")
                                if success?.blockStatus == "blocked" {
                                    self.view.makeToast("User has been blocked!!")
                                } else if success?.blockStatus == "un-blocked" {
                                    self.view.makeToast(NSLocalizedString("User has been unblocked!!", comment: "User has been unblocked!!"))
                                } else {
                                    self.view.makeToast(success?.blockStatus ?? "")
                                }
                                self.navigationController?.popViewController(animated: true)
                            }
                        }
                    } 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: Collection View Setup
extension UserProfileViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.media.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueCell(MediaCollectionViewCell.self, for: indexPath)
        let object = self.media[indexPath.row]
        let mediaUrl = URL(string: object.media ?? "")
        switch object.type {
        case "left_image", "right_image":
            let indicator = SDWebImageActivityIndicator.medium
            cell.mediaImageView.sd_imageIndicator = indicator
            DispatchQueue.global(qos: .userInteractive).async {
                cell.mediaImageView.sd_setImage(with: mediaUrl, placeholderImage: UIImage(named: ""))
            }
        case "left_video", "right_video":
            cell.subImageView.isHidden = false
            cell.subImageView.image = R.image.icon_play_vector()
            cell.subImageView.tintColor = .white
            cell.mediaImageView.image = UIImage(named: "")            
            self.generateThumbnail(from: mediaUrl!, completion: { image in
                cell.mediaImageView.image = image
            })
            player.pause()
        case "left_gif", "right_gif":
            let gifUrl = URL(string: object.media ?? "")
            let indicator = SDWebImageActivityIndicator.medium
            cell.mediaImageView.sd_imageIndicator = indicator
            DispatchQueue.global(qos: .userInteractive).async {
                cell.mediaImageView.sd_setImage(with: gifUrl)
            }
        case "left_file", "right_file":
            cell.mediaImageView.image = R.image.image_File()
        case "left_audio", "right_audio":
            cell.mediaImageView.image = R.image.audio_File()
        case "left_sticker", "right_sticker":
            let indicator = SDWebImageActivityIndicator.medium
            cell.mediaImageView.sd_imageIndicator = indicator
            DispatchQueue.global(qos: .userInteractive).async {
                cell.mediaImageView.sd_setImage(with: mediaUrl, placeholderImage: UIImage(named: ""))
            }
        default:
            break
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let object = self.media[indexPath.row]
        self.handleMediaClick(with: object, indexPath: indexPath)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let collectionHeight = collectionView.height
        return CGSize(width: collectionHeight, height: collectionHeight)
    }
    
    private func handleMediaClick(with object: MessageMedia, indexPath: IndexPath) {
        switch object.type {
        case "left_image", "right_image":
            self.handleImagePreview(indexPath: indexPath)
        case "left_video", "right_video":
            self.handleVideoFilePreview(indexPath: indexPath)
        case "left_gif", "right_gif":
            self.handleGifPreview(indexPath: indexPath)
        case "left_file", "right_file":
            self.handleDocumentFilePreview(indexPath: indexPath)
        case "left_audio", "right_audio":
            self.handleAudioFilePreview(indexPath: indexPath)
        case "left_sticker", "right_sticker":
            self.handleImagePreview(indexPath: indexPath)
        default:
            break
        }
    }
    
    // Handle Image Preview
    private func handleImagePreview(indexPath: IndexPath) {
        let object = self.media[indexPath.row]
        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)
    }
    
    // Handle Video File Preview
    func handleVideoFilePreview(indexPath: IndexPath) {
        let object = self.media[indexPath.row]
        let player = AVPlayer(url: URL(string: object.media ?? "")!)
        let vc = AVPlayerViewController()
        vc.player = player
        self.present(vc, animated: true) {
            vc.player?.play()
        }
    }
    
    // Handle Document File Preview
    func handleDocumentFilePreview(indexPath: IndexPath) {
        let object = self.media[indexPath.row]
        if let pdfURL = URL(string: object.media ?? "") {
            let safariViewController = SFSafariViewController(url: pdfURL)
            safariViewController.delegate = self
            present(safariViewController, animated: true, completion: nil)
        }
    }
    
    // Handle Gif Preview
    func handleGifPreview(indexPath: IndexPath) {
        let object = self.media[indexPath.row]
        let vc = R.storyboard.dashboard.showImageVC()
        vc?.imageURL = object.media ?? ""
        vc?.isGif = true
        vc?.modalPresentationStyle = .fullScreen
        vc?.modalTransitionStyle = .coverVertical
        self.present(vc!, animated: true, completion: nil)
    }
    
    // Handle Audio File Preview
    func handleAudioFilePreview(indexPath: IndexPath) {
        let object = self.media[indexPath.row]
        if let url = URL(string: object.media ?? "") {
            UIApplication.shared.open(url)
        }
    }
    
}

// MARK: MoreMenuViewControllerDelegate Methods
extension UserProfileViewController: UserProfileMenuAlertVCDelegate {
    
    func handleBlockButtonTap(_ sender: UIButton) {
        if self.user_data?.is_blocked ?? false {
            self.blockUser(block_action: "un-block")
        } else {
            self.blockUser(block_action: "block")
        }
    }
    
    func handleShareButtonTap(_ sender: UIButton) {
        if let name = URL(string: "\(API.baseURL)/\(self.user_data?.username ?? "")") {
            let objectsToShare = [name]
            let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
            self.present(activityVC, animated: true, completion: nil)
        }
    }
    
}

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

// MARK: MessageAlertVCDelegate Methods
extension UserProfileViewController: MessageAlertVCDelegate {
    
    func messageAlertConfirmButtonPressed(_ sender: UIButton) {
        self.followUser()
    }
    
}
