//
//  PlayController3.swift
//  tdvideo
//
//  Created by mac on 2024/2/1.
//


import UIKit
import PhotosUI
import AVKit
import MobileCoreServices

class PlayController3: UIViewController, PHPickerViewControllerDelegate {
    var imageView: UIImageView!
    var playerView: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        setupUI()
    }
    
    private func setupUI() {
        imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
        imageView.contentMode = .scaleAspectFit
        imageView.center = view.center
        imageView.backgroundColor = UIColor.brown
        view.addSubview(imageView)
        
        playerView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
        playerView.backgroundColor = .black
        playerView.center = view.center
        view.addSubview(playerView)
        
        let button = UIButton(type: .system)
        button.setTitle("Open Photo Album", for: .normal)
        button.addTarget(self, action: #selector(openPhotoAlbum), for: .touchUpInside)
        button.frame = CGRect(x: 0, y: 0, width: 200, height: 50)
        button.center = CGPoint(x: view.center.x, y: view.center.y + 250)
        view.addSubview(button)
    }
    
    @objc private func openPhotoAlbum() {
        var configuration = PHPickerConfiguration()
        configuration.selectionLimit = 1
        configuration.filter = .any(of: [.images, .videos])
        
        let picker = PHPickerViewController(configuration: configuration)
        picker.delegate = self
        present(picker, animated: true, completion: nil)
    }
    
    // MARK: - PHPickerViewControllerDelegate
    
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        picker.dismiss(animated: true, completion: nil)
        
        guard let result = results.first else {
            return
        }
        
        let itemProvider = result.itemProvider
        
        if itemProvider.canLoadObject(ofClass: UIImage.self) {
            itemProvider.loadObject(ofClass: UIImage.self) { [weak self] (image, error) in
                if let image = image as? UIImage {
                    DispatchQueue.main.async {
                        self?.imageView.image = image
                        self?.playerView.isHidden = true
                    }
                }
            }
        }
        
        let imageTypeIdentifier = kUTTypeImage as String
        let videoTypeIdentifier = kUTTypeMovie as String
        if itemProvider.hasItemConformingToTypeIdentifier(imageTypeIdentifier) {
            print("Item provider contains an image")
        }
                
        if itemProvider.hasItemConformingToTypeIdentifier(videoTypeIdentifier) {
            
            itemProvider.loadItem(forTypeIdentifier: videoTypeIdentifier, options: nil) { (item, error) in
                if let url = item as? URL {
                    let asset = AVAsset(url: url)
                    DispatchQueue.main.async {
                        let playerItem = AVPlayerItem(asset: asset)
                        let player = AVPlayer(playerItem: playerItem)
                        let playerLayer = AVPlayerLayer(player: player)
                        playerLayer.frame = self.playerView.bounds ?? CGRect.zero
                        self.playerView.layer.addSublayer(playerLayer)
                        player.play()
                        self.playerView.isHidden = false
                    }
                    
                }
            }
            
        }
        
    }
}
