//
//  ViewController2.swift
//  tdvideo
//
//  Created by mac on 2024/2/4.
// 视频转码


import UIKit
import AVKit
import AVFoundation
import CoreImage
import Foundation
import Observation
import VideoToolbox
import CoreMedia
import MobileCoreServices

//视频转码
class ViewController2: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
//    let convertor = VideoConvertor()
    let convertor2 = VideoConvertor2()
    
    let videoConverter = SpatialVideoConverter()
    var metview:MetalPlayer?
    
    var videoOriginalAsset:AVAsset?
    var videoTempAsset:AVAsset?
    
    var sourceVideoURL:URL?
    var outputVideoURL:URL?
    
    
    
    var playerLay:AVPlayerLayer?
    var player:AVPlayer = AVPlayer()
    var btn3:UIButton?
    
//    var selectedIndex = 0
    
    func startObserving() {
            let nc = NotificationCenter.default
            nc.addObserver(self, selector: #selector(handleNotification(_:)), name: NSNotification.Name(rawValue: "upvideo"), object: nil)
        }
        
    @objc func handleNotification(_ notification: Notification) {
        // 处理接收到的通知
        if notification.name.rawValue == "upvideo" {

            
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        startObserving()
        self.view.backgroundColor = UIColor.brown
        //是否支持空间视频编/解码功能：
//        print(VTIsStereoMVHEVCEncodeSupported())
        
        let btn1 = UIButton.init(frame: CGRect.init(x: 20, y: 120, width: 180, height: 50))
        btn1.setTitle("从相册选择视频", for: UIControl.State.normal)
        self.view.addSubview(btn1)
        btn1.tag = 10
        btn1.addTarget(self, action: #selector(buttonPressed(sender:)), for: UIControl.Event.touchUpInside)
//
//        let btn2 = UIButton.init(frame: CGRect.init(x: 250, y: 120, width: 100, height: 50))
//        btn2.setTitle("开始播放", for: UIControl.State.normal)
//        self.view.addSubview(btn2)
//        btn2.tag = 11
//        btn2.addTarget(self, action: #selector(buttonPressed(sender:)), for: UIControl.Event.touchUpInside)
        
        
        btn3 = UIButton.init(frame: CGRect.init(x: 150, y: 60, width: 180, height: 50))
        btn3!.setTitle("进度=0.0", for: UIControl.State.normal)
        self.view.addSubview(btn3!)
        btn3!.tag = 12
        
        
       let path = Bundle.main.path(forResource: "IMG_0071", ofType: "MOV")
        sourceVideoURL = URL.init(filePath: path!)
        outputVideoURL =  URL.documentsDirectory.appending(path:"output1111.mp4")
        videoOriginalAsset = AVAsset(url: sourceVideoURL!)
        videoTempAsset = videoOriginalAsset

        
        
        
        // 创建分段选择器
                let segmentedControl = UISegmentedControl(items: ["立体视频","空间视频", "交叉眼", "红蓝立体","高斯模糊"])
                // 设置分段选择器的位置和大小
                segmentedControl.frame = CGRect(x: 20, y: 700, width: 360, height: 45)
                // 设置默认选中的分段
                segmentedControl.selectedSegmentIndex = 0
                // 添加分段选择器到视图中
                self.view.addSubview(segmentedControl)
        segmentedControl.layer.borderWidth = 1.0 // 边框宽度
                segmentedControl.layer.borderColor = UIColor.blue.cgColor // 边框颜色
                segmentedControl.tintColor = UIColor.blue // 选中状态颜色
        let normalTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
                let selectedTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.blue]
                
                segmentedControl.setTitleTextAttributes(normalTextAttributes, for: .normal)
                segmentedControl.setTitleTextAttributes(selectedTextAttributes, for: .selected)
                // 添加分段选择器的事件处理
                segmentedControl.addTarget(self, action: #selector(segmentedControlValueChanged(_:)), for: .valueChanged)
        
        
        
        playerLay = AVPlayerLayer()
        playerLay!.backgroundColor = UIColor.black.cgColor
        playerLay!.frame = CGRect.init(x: 10, y: 180, width: 350, height: 380)
        self.view.layer.addSublayer(playerLay!)
        playerLay!.cornerRadius = 6
        
        play()
//        AVPlayerVideoOutput()
        
//        player.addPeriodicTimeObserver(
//            forInterval: CMTime(value: 1, timescale: 30),
//            queue: .main
//        ) { _ in
//
//
//        }
        
        
    }
    
    
    
    //播放
    func play(){
        
        let playerItem = AVPlayerItem(asset: videoTempAsset!)
        playerLay!.player = AVPlayer(playerItem: playerItem)
        playerLay!.player!.play()
    }
    
    
    @objc func segmentedControlValueChanged(_ sender: UISegmentedControl) {
            // 处理分段选择器值改变事件
        let selectedIndex = sender.selectedSegmentIndex
        print("选中了第 \(selectedIndex) 个选项")
        player.pause()
        NotificationCenter.default.removeObserver(self)

        //立体视频
        if(selectedIndex == 0){
            videoTempAsset = videoOriginalAsset
            play()
        }
        else{
            outputVideoURL = URL.documentsDirectory.appending(path:"output11112.mp4")
        }
        
        //空间视频
        if(selectedIndex == 1){
//            Task {
//                try await videoConverter.convertStereoscopicVideoToSpatialVideo(sourceVideoURL: sourceVideoURL!,outputVideoURL: outputVideoURL!){[weak self] progress in
//                    print(progress)
//                    DispatchQueue.main.async { [weak self] in
//                        self!.btn3!.setTitle("进度=" + String(progress), for: UIControl.State.normal)
//                        if(progress > 0.99){
//                            self!.videoTempAsset = AVAsset(url: self!.outputVideoURL!)
//                            self!.play()
//                        }
//                    }
//                }
//            }
        }
        //交叉眼
        if(selectedIndex == 2){
            Task {
                convertor2.type = 2
                
                try await convertor2.convertVideo(asset: videoTempAsset!, outputFile: outputVideoURL! ) { [self] progress in
                    print(progress)
                    DispatchQueue.main.async { [weak self] in
                        self!.btn3!.setTitle("进度=" + String(progress), for: UIControl.State.normal)
                        if(progress > 0.99){
                            self!.videoTempAsset = AVAsset(url: self!.outputVideoURL!)
                            self!.play()
                        }
                    }
                    
                }
            }
        }
        
        //红蓝立体
        if(selectedIndex == 3){
            Task {
                convertor2.type = 3
                
                try await convertor2.convertVideo(asset: videoTempAsset!, outputFile: outputVideoURL! ) { [self] progress in
                    print(progress)
                    DispatchQueue.main.async { [weak self] in
                        self!.btn3!.setTitle("进度=" + String(progress), for: UIControl.State.normal)
                        if(progress > 0.99){
                            self!.videoTempAsset = AVAsset(url: self!.outputVideoURL!)
                            self!.play()
                        }
                    }
                    
                }
            }
        }
        //高斯模糊
        if(selectedIndex == 4){
            Task {
                convertor2.type = 4
                
                try await convertor2.convertVideo(asset: videoTempAsset!, outputFile: outputVideoURL! ) { [self] progress in
                    print(progress)
                    DispatchQueue.main.async { [weak self] in
                        self!.btn3!.setTitle("进度=" + String(progress), for: UIControl.State.normal)
                        if(progress > 0.99){
                            self!.videoTempAsset = AVAsset(url: self!.outputVideoURL!)
                            self!.play()
                        }
                    }
                    
                }
            }
        }
    }
    
    @objc func buttonPressed(sender:UIButton){
        
        if(sender.tag == 10){
//            let imagePickerController = UIImagePickerController()
//            imagePickerController.delegate = self
//            imagePickerController.sourceType = .photoLibrary
//            imagePickerController.allowsEditing = false
//            imagePickerController.mediaTypes = [kUTTypeMovie as String]
//            present(imagePickerController, animated: true, completion: nil)
            
            let vc:PlayControllerVideo = PlayControllerVideo()
            self.present(vc, animated: true, completion: nil)
            vc.mediaSelectedHandler = { [self]ass in
                print("回调")
                print(ass)
                videoTempAsset = ass
                play()
            }
            
        } else{
            
        }
    }
    

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        

        if let mediaType = info[UIImagePickerController.InfoKey.mediaType] as? String, mediaType == "public.movie" {
            let videoURL = info[.mediaURL] as? URL
             print("Selected video URL: \(videoURL)")
             sourceVideoURL = videoURL
             videoOriginalAsset = AVAsset(url: sourceVideoURL!)
             videoTempAsset = videoOriginalAsset
            if(!isSpatialVideo(asset: videoTempAsset!)){
                showTextAlert(title: "提示", message: "当前视频不是空间视频")
            }
             play()
        }
        
        dismiss(animated: true, completion: nil)
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true, completion: nil)
    }
    
    //检查是否为空间视频
    func isSpatialVideo(asset: AVAsset) -> Bool {
            let metadata = asset.metadata(forFormat: AVMetadataFormat.quickTimeMetadata)
            let isSpatialVideo = metadata.contains { item in
                if let identifier = item.identifier?.rawValue {
                    return identifier == "mdta/com.apple.quicktime.spatial.format-version"
                }
                return false
            }
            return isSpatialVideo
    }

    func showTextAlert(title: String, message: String) {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alertController.addAction(okAction)
        
        // 在视图控制器中显示弹窗
        present(alertController, animated: true, completion: nil)
    }
    
}

