/* -LICENSE-START-
 ** Copyright (c) 2018 Blackmagic Design
 **
 ** Permission is hereby granted, free of charge, to any person or organization
 ** obtaining a copy of the software and accompanying documentation covered by
 ** this license (the "Software") to use, reproduce, display, distribute,
 ** execute, and transmit the Software, and to prepare derivative works of the
 ** Software, and to permit third-parties to whom the Software is furnished to
 ** do so, all subject to the following:
 **
 ** The copyright notices in the Software and this entire statement, including
 ** the above license grant, this restriction and the following disclaimer,
 ** must be included in all copies of the Software, in whole or in part, and
 ** all derivative works of the Software, unless such copies or derivative
 ** works are solely in the form of machine-executable object code generated by
 ** a source language processor.
 **
 ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 ** FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
 ** SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
 ** FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
 ** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 ** DEALINGS IN THE SOFTWARE.
 ** -LICENSE-END-
 */
#include <CoreGraphics/CGImage.h>
#include <Foundation/NSString.h>
#include <Foundation/NSURL.h>
#include <Foundation/NSFileManager.h>
#include <ImageIO/CGImageSource.h>

#include "ImageLoader.h"
#include "DeckLinkAPI.h"

static const int kBitsPerComponent = 8;

HRESULT ImageLoader::GetPNGFilesFromDir(const std::string& path, std::vector<std::string>& fileList)
{
	NSString* pngDirectory = [NSString stringWithUTF8String:path.c_str()];
	NSDirectoryEnumerator* fileEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:[pngDirectory stringByExpandingTildeInPath]];
	
	for (NSString* filename in fileEnumerator)
	{
		if ( [[filename pathExtension] isEqualToString:@"png"] )
		{
			fileList.push_back(std::string([[pngDirectory stringByAppendingPathComponent:filename] UTF8String]));
		}
	}
	
	return S_OK;
}

HRESULT ImageLoader::ConvertPNGToDeckLinkVideoFrame(const std::string& pngFilename, IDeckLinkVideoFrame* deckLinkVideoFrame)
{
	CGImageSourceRef imageSource = CGImageSourceCreateWithURL((CFURLRef)[NSURL fileURLWithPath:[[NSString stringWithUTF8String:pngFilename.c_str()] stringByExpandingTildeInPath]], NULL);

	if (imageSource == NULL)
		return E_FAIL;

	// Create an image from the first item in the image source.
	CGImageRef cgImage = CGImageSourceCreateImageAtIndex(imageSource, 0, NULL);
	CFRelease(imageSource);

	long imageWidth = CGImageGetWidth(cgImage);
	long imageHeight = CGImageGetHeight(cgImage);
	
	long videoFrameWidth = deckLinkVideoFrame->GetWidth();
	long videoFrameHeight = deckLinkVideoFrame->GetHeight();
	long videoFrameRowBytes = deckLinkVideoFrame->GetRowBytes();

	CGImageRef cgCroppedImage;
	
	// If image is larger than video frame size, then crop it
	CGRect cropRect;
	cropRect.origin.x = MAX((imageWidth - videoFrameWidth) / 2, 0);
	cropRect.origin.y = MAX((imageHeight - videoFrameHeight) / 2, 0);
	cropRect.size.width = MIN(imageWidth, videoFrameWidth);
	cropRect.size.height = MIN(imageHeight, videoFrameHeight);
		
	cgCroppedImage = CGImageCreateWithImageInRect(cgImage, cropRect);
	CGImageRelease(cgImage);
	
	imageWidth = CGImageGetWidth(cgCroppedImage);
	imageHeight = CGImageGetHeight(cgCroppedImage);
	
	// Get a pointer to the DeckLink video frame's buffer
	void* deckLinkFrameBuffer = NULL;
	deckLinkVideoFrame->GetBytes(&deckLinkFrameBuffer);

	// Clear buffer in video frame, so we can display image smaller than the video frame size without artifacts
	memset(deckLinkFrameBuffer, 0, videoFrameRowBytes * videoFrameHeight);

	// Copy/convert the source image into the DeckLink video frame's buffer
	CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

	CGContextRef context = CGBitmapContextCreate(deckLinkFrameBuffer, videoFrameWidth, videoFrameHeight, kBitsPerComponent,
												 videoFrameRowBytes, colorSpace,
												 kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
	
	// Center image in drawing context
	CGRect drawRect;
	drawRect.origin.x = MAX((videoFrameWidth - imageWidth) / 2, 0);
	drawRect.origin.y = MAX((videoFrameHeight - imageHeight) / 2, 0);
	drawRect.size.width = imageWidth;
	drawRect.size.height = imageHeight;
	
	CGContextDrawImage(context, drawRect, cgCroppedImage);

	CGColorSpaceRelease(colorSpace);
	CGContextRelease(context);
	CGImageRelease(cgCroppedImage);

	return S_OK;
}
