//
//  HelperFunctions.swift
//  MetalForBeginners
//
//  Created by Alex Hoppen on 26.07.19.
//  Copyright © 2019 Alex Hoppen. All rights reserved.
//

import Cocoa

extension NSImage {
    convenience init(rawBuffer: UnsafeBufferPointer<UInt32>, width: Int, height: Int) {
        let cgImageDataProvider = CGDataProvider(data: Data(buffer: rawBuffer) as CFData)!
        
        let cgImage = CGImage(width: width, height: height,
                              bitsPerComponent: 8,
                              bitsPerPixel: MemoryLayout<UInt32>.size * 8,
                              bytesPerRow: width * MemoryLayout<UInt32>.size,
                              space: CGColorSpace(name: CGColorSpace.sRGB)!,
                              bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue),
                              provider: cgImageDataProvider,
                              decode: nil,
                              shouldInterpolate: false,
                              intent: CGColorRenderingIntent.defaultIntent)
        
        self.init(cgImage: cgImage!, size: NSSize(width: width, height: height))
    }
    
    @discardableResult
    func writeRawIntoBuffer(_ buffer: UnsafeMutableBufferPointer<UInt32>, width: Int, height: Int) -> CGContext {
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bytesPerRow = 4 * width
        let bitsPerComponent = 8
        let context = CGContext(data: buffer.baseAddress,
                                width: width,
                                height: height,
                                bitsPerComponent: bitsPerComponent,
                                bytesPerRow: bytesPerRow,
                                space: colorSpace,
                                bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue)!
        
        // Draw the image into the memory buffer
        context.draw(self.cgImage(forProposedRect: nil, context: nil, hints: nil)!, in: CGRect(x: 0, y: 0, width: width, height: height))
        context.makeImage()
        
        return context
    }
}


func displayImage(image: NSImage) {
    DispatchQueue.main.async {
        let imageView = NSImageView(frame: NSRect(x: 10, y: 10, width: 400, height: 300))
        imageView.image = image
        NSApplication.shared.windows[0].contentView?.addSubview(imageView)
    }
}
