//
//  CCSpatialShootController+SessionConfigure.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 {
    
     func configureSession() {
        session.beginConfiguration()
        defer {
            session.commitConfiguration()
        }
        
        // 配置后置摄像头  .builtInWideAngleCamera 广角摄像头(默认设备 --- 主摄，28mm左右焦段)   .back 后置摄像头
        guard let backCamera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) else {
            print("Could not find the back camera")
            return
        }
        wideAngleCameraDevice = backCamera
        
        do {
            wideAngleCameraDeviceInput = try AVCaptureDeviceInput(device: backCamera)
            
            guard let wideAngleCameraDeviceInput = wideAngleCameraDeviceInput,
                  session.canAddInput(wideAngleCameraDeviceInput) else {
                print("Could not add back camera input")
                return
            }
            session.addInput(wideAngleCameraDeviceInput)
        } catch {
            print("Could not create back camera device input: \(error)")
            return
        }
        
        //   .builtInUltraWideCamera  超广角(默认设备的0.5x，只能使用AVCaptureDeviceDiscoverySession获取)    .back 后置摄像头
        guard let frontCamera = AVCaptureDevice.default(.builtInUltraWideCamera, for: .video, position: .back) else {
            print("Could not find the front camera")
            return
        }
        
        do {
            print("builtInUltraWideCamera:\(frontCamera.videoZoomFactor)")
            
            // 设置焦距
//            frontCamera.focusMode = .autoFocus
            ultraWideCameraDeviceInput = try AVCaptureDeviceInput(device: frontCamera)
            guard let ultraWideCameraDeviceInput = ultraWideCameraDeviceInput,
                  session.canAddInput(ultraWideCameraDeviceInput) else {
                print("Could not add front camera input")
                return
            }
            session.addInput(ultraWideCameraDeviceInput)
        } catch {
            print("Could not create front camera device input: \(error)")
            return
        }
        
        // 配置音频输入设备
        guard let audioDevice = AVCaptureDevice.default(for: .audio) else {
            print("Could not find audio device")
            return
        }
        
        do {
            let audioDeviceInput = try AVCaptureDeviceInput(device: audioDevice)
            
            guard session.canAddInput(audioDeviceInput) else {
                print("Could not add audio input")
                return
            }
            
            session.addInput(audioDeviceInput)
        } catch {
            print("Could not create audio device input: \(error)")
            return
        }
        
        // 配置广角摄像头输出
//        wideAngleCameraMovieOutput = AVCaptureMovieFileOutput()
//        guard let wideAngleCameraMovieOutput = wideAngleCameraMovieOutput,
//              session.canAddOutput(wideAngleCameraMovieOutput) else {
//            print("Could not add the back camera movie output")
//            return
//        }
//        session.addOutput(wideAngleCameraMovieOutput)
        
        wideAngleCameraVideoDataOutput = AVCaptureVideoDataOutput()
//        svdWriter.videoSettings = wideAngleCameraVideoDataOutput?.recommendedVideoSettingsForAssetWriter(writingTo: .heic)
        guard let wideAngleCameraVideoDataOutput, session.canAddOutput(wideAngleCameraVideoDataOutput) else {
            print("wideAngleCameraVideoDataOutput....")
            return
        }
        wideAngleCameraVideoDataOutput.setSampleBufferDelegate(self, queue: DispatchQueue.global())
        wideAngleCameraVideoDataOutput.alwaysDiscardsLateVideoFrames = true
        wideAngleCameraVideoDataOutput.videoSettings = [
            kCVPixelBufferPixelFormatTypeKey as String: Int(kCVPixelFormatType_32BGRA),
        ]
//         wideAngleCameraVideoDataOutput.videoSettings =
//                     [NSDictionary dictionaryWithObject:
//                         [NSNumber numberWithInt:kCVPixelFormatType_32BGRA]
//                         forKey:(id)kCVPixelBufferPixelFormatTypeKey];
//         wideAngleCameraVideoDataOutput.minFrameDuration = CMTimeMake(1, 15);
        session.addOutput(wideAngleCameraVideoDataOutput)
        
        // 配置超广角摄像头输出
//        ultraWideCameraMovieOutput = AVCaptureMovieFileOutput()
//        guard let ultraWideCameraMovieOutput = ultraWideCameraMovieOutput,
//              session.canAddOutput(ultraWideCameraMovieOutput) else {
//            print("Could not add the front camera movie output")
//            return
//        }
//        session.addOutput(ultraWideCameraMovieOutput)
        
        ultraWideCameraVideoDataOutput = AVCaptureVideoDataOutput()
        guard let ultraWideCameraVideoDataOutput,
              session.canAddOutput(ultraWideCameraVideoDataOutput) else {
            print("ultraWideCameraVideoDataOutput....")
            return
        }
        ultraWideCameraVideoDataOutput.alwaysDiscardsLateVideoFrames = true
        ultraWideCameraVideoDataOutput.setSampleBufferDelegate(self, queue: DispatchQueue.global())
        ultraWideCameraVideoDataOutput.videoSettings = [
                      kCVPixelBufferPixelFormatTypeKey as String: Int(kCVPixelFormatType_32BGRA),
                  ]
//         svdWriter.videoSettings = wideAngleCameraVideoDataOutput.recommendedVideoSettingsForAssetWriter(writingTo: .mov)
        session.addOutput(ultraWideCameraVideoDataOutput)
        
         
        //配置声音输出
        wuCameraAudioDataOutput = AVCaptureAudioDataOutput()
        guard let wuCameraAudioDataOutput,
              session.canAddOutput(wuCameraAudioDataOutput) else {
            print("wuCameraAudioDataOutput....")
            return
        }
         wuCameraAudioDataOutput.setSampleBufferDelegate(self, queue: DispatchQueue.global())
        session.addOutput(wuCameraAudioDataOutput)
        
        //
        
        // 配置预览图层 --- 主摄
        wideAngleCameraVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
        wideAngleCameraVideoPreviewLayer?.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)
        if let wideAngleCameraVideoPreviewLayer = wideAngleCameraVideoPreviewLayer {
            wideAngleCameraVideoPreviewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
            self.view.layer.insertSublayer(wideAngleCameraVideoPreviewLayer, at: 0)
        }

         
        DispatchQueue.global().async {
            self.session.startRunning()

            //变焦设置需要在AVCaptureMultiCamSession statrunning之后设置才会生效
            try! frontCamera.lockForConfiguration()
            frontCamera.videoZoomFactor = 1.75//变焦
            frontCamera.unlockForConfiguration()
            
        }
    }
    
}
