/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

#import "OpenVulkanoViewController.h"

#include <MoltenVK/mvk_vulkan.h>
#include "Host/GraphicsAppManager.hpp"
#include "Base/UI/IVulkanWindow.hpp"

#import <MetalKit/MTKView.h>
#import "OpenVulkanoView.h"

#pragma mark -
#pragma mark OpenVulkanoViewController

using namespace OpenVulkano;


@implementation OpenVulkanoViewController {
	GraphicsAppManager* manager;
	std::unique_ptr<IGraphicsApp> app;
}

-(void*) makeGraphicsApp {
	return nullptr;
}

-(id)init {
	[super init];
	_openVulkanoView = nil;
	return self;
}

-(void) dealloc {
	manager->ShutDown();
	delete manager;
	app = nullptr;
	//TODO figure out where these two references are held
	[_openVulkanoView release];
	[_openVulkanoView release];
	_openVulkanoView = nil;
	[super dealloc];
}

/** Since this is a single-view app, init Vulkan when the view is loaded. */
-(void) viewDidLoad {
	[super viewDidLoad];

	if (_openVulkanoView == nil && [self.view isKindOfClass:[OpenVulkanoView class]]) {
		_openVulkanoView = (OpenVulkanoView*)self.view;
	}
	
	//TODO check if type is correct
	IGraphicsApp* appPtr = static_cast<IGraphicsApp*>(self.makeGraphicsApp);
	if (!appPtr) throw std::runtime_error("Failed to create graphics app");
	app = std::unique_ptr<IGraphicsApp>(appPtr);
	manager = new GraphicsAppManager(app.get(), (IVulkanWindow*)[_openVulkanoView GetWindow]);
	manager->StartUp();
}

-(void) viewWillAppear:(BOOL)animated {
	if (_openVulkanoView != nil) { [_openVulkanoView WillAppear]; }
	[super viewWillAppear:animated];
}

-(void) viewDidAppear:(BOOL)animated {
	if (_openVulkanoView != nil) { [_openVulkanoView DidAppear]; }
	[super viewDidAppear:animated];
}

-(void) viewWillDisappear:(BOOL)animated {
	if (_openVulkanoView != nil) { [_openVulkanoView WillDisappear]; }
	[super viewWillDisappear:animated];
}

-(void) viewDidDisappear:(BOOL)animated {
	if (_openVulkanoView != nil) { [_openVulkanoView DidDisappear]; }
	[super viewDidDisappear:animated];
}

-(void) viewDidUnload {
	if (_openVulkanoView != nil) { [_openVulkanoView DidUnload]; }
	[super viewDidUnload];
}

-(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id)coordinator {
	[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
}

- (BOOL)prefersHomeIndicatorAutoHidden {
	return true;
}
@end


