import CoreGraphics
import Metal

// Work around for macOS and simulator not having [[ color(0) ]]
public class CurrentColorCapture: NSObject {
    
    public var textureBuffer: MTLTexture?
    private var size = SIMD2<Int>(0, 0)
    
    override public init() {
        super.init()
    }
    
    public func setupTexture(size cgSize: CGSize) {
        size = SIMD2<Int>(Int(floor(cgSize.width)), Int(floor(cgSize.height)))
        let descriptor = MTLTextureDescriptor()
        descriptor.textureType = .type2D
        descriptor.pixelFormat = .bgra8Unorm
        descriptor.width = size.x
        descriptor.height = size.y
        descriptor.usage = [.shaderRead, .renderTarget]
        textureBuffer = Adamantium.sharedDevice?.makeTexture(descriptor: descriptor)
    }
    
    public func captureColor(commandBuffer: MTLCommandBuffer, currentTexture: MTLTexture) {
        guard
            let blit = commandBuffer.makeBlitCommandEncoder(),
            let textureBuffer = textureBuffer
        else { return }
        if #available(iOS 13.0, *) {
            blit.copy(from: currentTexture, to: textureBuffer)
        } else {
            // Fallback on earlier versions
        }
        blit.endEncoding()
    }
}

extension CurrentColorCapture {
    enum Constants {
        static let zeroOrigin = MTLOrigin(x: 0, y: 0, z: 0)
    }
}
