//
//  MediaViewController.swift
//  WoWonder
//
//  Created by Mohammed Hamad on 29/08/2022.
//  Copyright © 2022 ScriptSun. All rights reserved.
//

import UIKit
import AVKit
import SafariServices
import SDWebImage

class MediaViewController: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    // MARK: - Properties
    
    var messageArray: [Messages] = []
    var media: [MessageMedia] = []
    var user_id = ""
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        self.initialConfig()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.navigationController?.navigationBar.isHidden = true
    }
    
    // MARK: - Selectors
    
    // Back Button Action
    @IBAction func backButtonAction(_ sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.registerCell()
        self.setData()
    }
    
    // Register Cell
    func registerCell() {
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.collectionView.register(UINib(resource: R.nib.mediaCollectionViewCell), forCellWithReuseIdentifier: R.reuseIdentifier.mediaCollectionViewCell.identifier)
    }
    
    // Set Data
    func setData() {
        if self.media.count == 0 {
            if self.messageArray.count == 0 {
                if let chat = Chats.getChatByUserID(self.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)
                }
            }
            self.collectionView.reloadData()
        }
    }
    
}

// MARK: - Extensions

// MARK: Collection View Setup
extension MediaViewController: 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 = self.collectionView.dequeueReusableCell(withReuseIdentifier: R.reuseIdentifier.mediaCollectionViewCell.identifier, for: indexPath) as! MediaCollectionViewCell
        let object = self.media[indexPath.row]
        let mediaUrl = URL(string: object.media ?? "")
        cell.subImageView.isHidden = true
        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
            })
        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) {
        if collectionView == self.collectionView {
            let object = self.media[indexPath.row]
            self.handleMediaClick(with: object, indexPath: indexPath)
        }        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let cellsInRow: CGFloat = 3
        let flowLayout: UICollectionViewFlowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        let leftRightPadding: CGFloat = flowLayout.sectionInset.left + flowLayout.sectionInset.right
        let spaceBetweenCells: CGFloat = flowLayout.minimumInteritemSpacing * cellsInRow
        let cellWidth = (collectionView.width - leftRightPadding - spaceBetweenCells) / cellsInRow
        return CGSize(width: cellWidth, height: cellWidth)
    }
    
    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: SFSafariViewControllerDelegate Methods
extension MediaViewController: SFSafariViewControllerDelegate {
    
    func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
        controller.dismiss(animated: true, completion: nil)
    }
    
}
