//
//  CCSpatialShootController+Generate.swift
//  SwiftProject
//
//  Created by aaa on 2024/5/20.
//

import Foundation
import AVFoundation
import Photos
import AVKit
import VideoToolbox
import SVProgressHUD
import Firebase
import CoreMotion

extension CCSpatialShootController: AVCaptureAudioDataOutputSampleBufferDelegate,AVCaptureVideoDataOutputSampleBufferDelegate {
    
    //视频、音频回调
    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
        if shootingMode == .CCShootingMode_Camera {
            takePhotoSemaphore.wait()
            if self.isTakePhoto {
                print("xxsddd:\(Thread.current)")
                
                if output == wideAngleCameraVideoDataOutput && self.isTakePhoto_wideCamera {
                    if let firstFrame = imageFromSampleBuffer(sampleBuffer: sampleBuffer,orientation: connection.videoOrientation) {
                        imgs.add(firstFrame)
                        self.isTakePhoto_wideCamera = false
                    }
                    else {
                        print("wide Angle firstframe is lost....")
                    }
                } else if output == ultraWideCameraVideoDataOutput && self.isTakePhoto_ultraCamera{
                    if let firstFrame = imageFromSampleBuffer(sampleBuffer: sampleBuffer,orientation: connection.videoOrientation)  {
                        imgs.add(firstFrame)
                        self.isTakePhoto_ultraCamera = false
                    }
                    else{
                        print("ultra Wide firstFrame is lost....")
                    }
                }
                
                if(imgs.count == 2){
                    compositeSpatialPhoto()
                    imgs.removeAllObjects()
                    self.isTakePhoto = false
                    print("2张照片满足合成....")
                }
                else {
                    print("images 少于2张....")
                }
            }
            
            takePhotoSemaphore.signal()
            
        }

        else if shootingMode == .CCShootingMode_Video {
            if isRecordingVideoData {
                
                if output == wideAngleCameraVideoDataOutput {//广角视频
                    writeVideoQueuen.async {[weak self] in//串行 异步执行
                        self?.svdWriter.exAddLeftSampleBuffer(sampleBuffer)
                    }
                }
                else if output == ultraWideCameraVideoDataOutput {//超广角视频
                    writeVideoQueuen.async {[weak self] in//串行 异步执行
                        self?.svdWriter.exAddRightSampleBuffer(sampleBuffer)
                    }
                }
                else if output == wuCameraAudioDataOutput {//音频
                    writeVideoQueuen.async {[weak self] in//串行 异步执行
                        self?.svdWriter.exAddAudioSampleBuffer(sampleBuffer)
                    }
                }

            }
        }
    }
    

    
    //视频掉帧回调
    func captureOutput(_ output: AVCaptureOutput, didDrop sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
        print("录制视频掉帧了...")
    }
    
    
    
    
    
    //通过samplebuffer生成uiimage
    func imageFromSampleBuffer(sampleBuffer: CMSampleBuffer,orientation:AVCaptureVideoOrientation ) -> UIImage? {
        guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return nil }
        let ciImage = CIImage(cvPixelBuffer: imageBuffer)
        let temporaryContext = CIContext(options: nil)
        guard let cgImage = temporaryContext.createCGImage(ciImage, from: ciImage.extent) else { return nil }
        print("rect:\(ciImage.extent)")
        let image = UIImage(cgImage: cgImage, scale: UIScreen.main.scale, orientation: getImgOrientation(orientation: orientation))
        return image
    }
    
    func getImgOrientation(orientation:AVCaptureVideoOrientation )->UIImage.Orientation {
        switch orientation {
        case .portrait:
            return .up
        case .portraitUpsideDown:
            return .down
        case .landscapeRight:
            return .right
        case .landscapeLeft:
            return .left
        }
    }
    
 
    
    //跟视频相关
     func removeExistingFile(at outputVideoURL: URL)  {
         if FileManager.default.fileExists(atPath: outputVideoURL.path) {
             do {
                 try FileManager.default.removeItem(atPath: outputVideoURL.path)
                 print("视频文件删除成功")
             } catch {
                 print("删除视频文件出错：\(error)")
             }
         }
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    
}
