//
//  PQVideoSnapshotUtil.swift
//  PQSpeed
//
//  Created by SanW on 2020/8/14.
//  Copyright © 2020 BytesFlow. All rights reserved.
//

import AVFoundation
import AVKit
import UIKit

public class PQVideoSnapshotUtil: NSObject {
    /// AVPlayer截屏
    /// - Parameter playerItem: <#playerItem description#>
    /// - Returns: <#description#>
    class public  func snapshotImage(avPlayer: AVPlayer, complateHandle: @escaping (_ image: UIImage?) -> Void) {
        guard let playerItem = avPlayer.currentItem else { // playerItem is AVPlayerItem
            complateHandle(nil)
            return
        }
        let videoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: nil)
        playerItem.add(videoOutput)
        let time = videoOutput.itemTime(forHostTime: CACurrentMediaTime())
        if videoOutput.hasNewPixelBuffer(forItemTime: time) {
            let lastSnapshotPixelBuffer = videoOutput.copyPixelBuffer(forItemTime: time, itemTimeForDisplay: nil)
            if lastSnapshotPixelBuffer != nil {
                let ciImage = CIImage(cvPixelBuffer: lastSnapshotPixelBuffer!)
                let context = CIContext(options: nil)
                let rect = CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(CVPixelBufferGetWidth(lastSnapshotPixelBuffer!)), height: CGFloat(CVPixelBufferGetHeight(lastSnapshotPixelBuffer!)))
                let cgImage = context.createCGImage(ciImage, from: rect)
                if cgImage != nil {
                    complateHandle(UIImage(cgImage: cgImage!))
                    return
                }
            }
        } else {
            complateHandle(nil)
        }
    }

    /// 非m3u8视频截屏
    /// - Parameters:
    ///   - videoURL: 视频地址
    ///   - time: 视频某个时间点
    /// - Returns: <#description#>
    class public  func videoSnapshot(videoURL: URL, time: TimeInterval) -> UIImage? {
        let asset = AVURLAsset(url: videoURL, options: avAssertOptions)
        let assetImageGenerator = AVAssetImageGenerator(asset: asset)
        assetImageGenerator.appliesPreferredTrackTransform = true
        assetImageGenerator.requestedTimeToleranceBefore = CMTime.zero
        assetImageGenerator.requestedTimeToleranceAfter = CMTime.zero
        assetImageGenerator.apertureMode = .encodedPixels
        let thumbnailCGImage: CGImage?
        let thumbnailImageTime: CFTimeInterval = time
        var thumbnailImage: UIImage?
        do {
            thumbnailCGImage = try assetImageGenerator.copyCGImage(at: CMTimeMake(value: Int64(thumbnailImageTime), timescale: 1), actualTime: nil)
            if let cgImage = thumbnailCGImage {
                thumbnailImage = UIImage(cgImage: cgImage)
            }
        } catch {}
        return thumbnailImage
    }

    /// 获取非m3u8多张视频截图
    /// - Parameters:
    ///   - videoURL: 视频地址
    ///   - duration: 视频时长
    ///   - count: 截取数量
    /// - Returns: <#description#>
    class public  func videoSnapshot(videoURL: URL, duration: TimeInterval, count: Int, complateHandle: @escaping ([UIImage]?) -> Void) {
        DispatchQueue.global().async {
            var images: [UIImage]? = Array()
            let asset = AVURLAsset(url: videoURL, options: avAssertOptions)
            let assetImageGenerator = AVAssetImageGenerator(asset: asset)
            assetImageGenerator.requestedTimeToleranceBefore = CMTime.zero
            assetImageGenerator.requestedTimeToleranceAfter = CMTime.zero
            assetImageGenerator.appliesPreferredTrackTransform = true
            assetImageGenerator.apertureMode = .encodedPixels
            for index in 0...count - 1 {
                let thumbnailCGImage: CGImage?
                let thumbnailImageTime: CFTimeInterval = ((duration / Double(count)) * Double(index))
                BFLog(message: "截取视频时长 =（\(videoURL),duration = \(duration),count = \(count),line = \(thumbnailImageTime)")
                do {
                    thumbnailCGImage = try assetImageGenerator.copyCGImage(at: CMTimeMake(value: Int64(thumbnailImageTime), timescale: 1), actualTime: nil)
                    if let cgImage = thumbnailCGImage {
                        images?.append(UIImage(cgImage: cgImage))
                    }
                } catch {}
            }
            complateHandle(images)
        }
    }
}
