//
//  SpeakCameraView.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/30.
//

import UIKit
import AVFoundation

class SpeakCameraView: UIView {
    // 捕获会话
    private let captureSession = AVCaptureSession()
    // 视频预览图层
    private let previewLayer = AVCaptureVideoPreviewLayer()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupCamera()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        setupCamera()
    }
    
    
    private func setupCamera() {
        // 设置会话质量
        clipsToBounds = true
        corners = 16
        captureSession.sessionPreset = .hd1920x1080
        // 获取前置摄像头
        guard let frontCamera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .front) else {
            print("无法获取前置摄像头")
            return
        }
        // 创建设备输入
        do {
            let input = try AVCaptureDeviceInput(device: frontCamera)
            // 将输入添加到会话
            if captureSession.canAddInput(input) {
                captureSession.addInput(input)
            }
            // 配置预览图层
            previewLayer.session = captureSession
            previewLayer.videoGravity = .resizeAspectFill
            // 将预览图层添加到视图的图层
            self.layer.addSublayer(previewLayer)
        } catch {
            print("设置摄像头输入失败: \(error)")
        }
    }
    
    @objc public func startCamera() {
        // 调整预览图层的大小以匹配视图
        previewLayer.frame = bounds
        // 开始捕获会话（异步执行以避免阻塞主线程）
        DispatchQueue.global(qos: .userInitiated).async {
            self.captureSession.startRunning()
        }
    }
    
    @objc public func stopCamera() {
        // 停止捕获会话
        captureSession.stopRunning()
    }
}
