//
//  CCSpatialVideoDisplayForVideoTask.swift
//  SwiftProject
//
//  Created by aaa on 2024/3/28.
//

import Foundation
import AVFoundation
import Photos
import AVKit
import VideoToolbox

extension CCSpatialVideoDisplayController {
    func getPlayerItem() -> AVPlayerItem {
        let temItem = AVPlayerItem(asset: self.videoOriginalAsset)
       AVVideoComposition.videoComposition(with: temItem.asset) { [weak self] request in
//           print("正在请求解码图片frame....")
           guard let weakSelf = self else {
               print("self 被销毁了.....")
               return
           }
           weakSelf.convertFrame(request:request)
        } completionHandler: { ac, err in
            if err != nil {
                print("初始化coposition报错：\(err)")
            }
            else{
                print("composition 生成ok....")
                temItem.videoComposition = ac
            }
        }

        return temItem
    }
    
    func convertFrame(request:AVAsynchronousCIImageFilteringRequest){
        let compositionTime = request.compositionTime
        let end:CMTime = CMTimeMake(value: Int64(compositionTime.value+1), timescale: compositionTime.timescale)
        let tr = CMTimeRange(start: compositionTime, end: end)
//        let tr_All = CMTimeRange(start: compositionTime, duration: .positiveInfinity)

        
        

        var ciImg:CIImage? = nil
        switch self.selectedIndex {
            case .monocular2D://双眼2d
            ciImg = request.sourceImage
            break
            
        default :
            ciImg = self.otherModeImgWithMode(mode: self.selectedIndex,tr:tr,compositionTime: compositionTime)
            break
        }
        if let ciImg {
//            print("已返回图片frame....")
            request.finish(with: ciImg, context: nil)
        }
        else {
//            print("没有合成可用视频帧图片....准备用request.sourceImage替换")
            request.finish(with: request.sourceImage, context: nil)
        }
    }
    
    func otherModeImgWithMode(mode:SpatialType,tr:CMTimeRange,compositionTime:CMTime)->CIImage? {
        guard let ao = self.assetOutput else {
            print("assetOutput 应该是没有被创建成功.....")
            return nil
        }
//        if needRestReaderTimeRange {
            while ao.copyNextSampleBuffer() != nil {
//                print("正在遍历。。。。1")
            }
            guard self.assetReader?.status == .reading else {
//                print("assetReader status:\(self.assetReader?.status) err:\(self.assetReader?.error)")
                return nil
            }
            ao.reset(forReadingTimeRanges:[NSValue(timeRange: tr)])
//        }
        
        
//        print("mode:......\(mode)")
        var ciImg:CIImage? = nil
        switch mode {
        case .crossedEyes://交叉眼
            ciImg = self.videoTranserConvertor.convertVideo(asset: self.videoOriginalAsset, assetOutput: ao, type: self.selectedIndex, time: compositionTime)
            break
        
        
        case .fsbs://3d全宽
            ciImg = self.videoTranserConvertor.convertVideo(asset: self.videoOriginalAsset, assetOutput: ao, type: self.selectedIndex, time: compositionTime)
            break
        
        
        case .hsbs://3d半宽
            ciImg = self.videoTranserConvertor.convertVideo(asset: self.videoOriginalAsset, assetOutput: ao, type: self.selectedIndex, time: compositionTime)
            break
        
        
        case .parallelEyes://平行眼
            ciImg = self.videoTranserConvertor.convertVideo(asset: self.videoOriginalAsset, assetOutput: ao, type: self.selectedIndex, time: compositionTime)
            break
        
        case .redBlueSolid://红蓝立体
            ciImg = self.videoTranserConvertor.convertVideo(asset: self.videoOriginalAsset, assetOutput: ao, type: self.selectedIndex, time: compositionTime)
            break
        default:
            break
        }
        return ciImg
            
    }
    
    //加载assetReader和output
    func loadVideoAssetReader() async {
        do {
            if  self.assetTrack == nil {
                assetTrack = try await self.videoOriginalAsset.loadTracks(withMediaType: .video).first!
            }
            let timeRange = CMTimeRange(start: .zero, duration: CMTime(value: 1, timescale: 1))
            DispatchQueue.main.async {
                self.quickLoadAReader(timeRange: timeRange)
            }
            
            
        } catch {
            print("Error loading video: \(error)")
        }
        
    }
    
    func quickLoadAReader(timeRange:CMTimeRange) {
        if(assetOutput != nil){
            assetOutput?.markConfigurationAsFinal()
            assetOutput = nil
        }
        if(assetReader != nil){
            assetReader?.cancelReading()
        }
        assetReader = try! AVAssetReader(asset: self.videoOriginalAsset)
        assetOutput = AVAssetReaderTrackOutput(
            track: self.assetTrack!,
            outputSettings: [
                AVVideoDecompressionPropertiesKey: [
                    kVTDecompressionPropertyKey_RequestedMVHEVCVideoLayerIDs: [0, 1] as CFArray,
                ],
            ]
        )
        assetOutput?.supportsRandomAccess = true
        assetOutput?.alwaysCopiesSampleData = false
        assetReader!.timeRange = timeRange
        assetReader!.add(assetOutput!)
        assetReader!.startReading()
        //加载完毕之后再进行play
//        DispatchQueue.main.async {
//
//            self.player?.play()
//
//            print("资产加载完毕。。。。开始播放player\n err:\(self.player?.error)")
//        }
    }
}
