//
//  XTTads3Entry.m
//  TadsTerp
//
//  Created by Rune Berg on 23/05/14.
//  Copyright (c) 2014 Rune Berg. All rights reserved.
//

#import "XTTads3Entry.h"

#include "osifcext.h"
#include "osxtads.h"
#include "appctx.h"
#include "vmmaincn.h"
#include "XTTads2AppCtx.h"
#include "XTVmHostIfc.h"
#import "XTAllocDeallocCounter.h"


@interface XTTads3Entry ()

//TODO assign is exp
@property (assign) CVmMainClientIfc *clientifc;
@property XTTads2AppCtx *t2AppCtx;
@property (assign) CVmHostIfc *hostifc;

@end


@implementation XTTads3Entry

OVERRIDE_ALLOC_FOR_COUNTER

OVERRIDE_DEALLOC_FOR_COUNTER

- (id)init
{
	self = [super init];
	if (self != nil) {
		_clientifc = new CVmMainClientConsole();
		_t2AppCtx = [XTTads2AppCtx context];
		_hostifc = new XTVmHostIfc([_t2AppCtx getAppCtxPtr]);
			//TODO mv to runTads3Game so we can pass res root dir to XTVmHostIfc::XTVmHostIfc and CResLoader
	}
	return self;
}

- (void)runTads3Game:(XTRunGameParams *)runGameParams
	  showTerpBanner:(BOOL)showTerpBanner
{
	const char* gameFileNameC = [runGameParams.gameFileUrl fileSystemRepresentation];
	
	vm_run_image_params params(self.clientifc, self.hostifc, gameFileNameC);
	
	params.show_banner = (int)showTerpBanner;
	
	if (runGameParams.saveFileUrl != nil) {
		params.saved_state = [runGameParams.saveFileUrl fileSystemRepresentation];
	}
	
	if (runGameParams.commandScriptAction == XT_CMD_SCRIPT_ACTION_RECORD) {
		params.cmd_log_file = [runGameParams.commandScriptFileUrl fileSystemRepresentation];
	} else if (runGameParams.commandScriptAction == XT_CMD_SCRIPT_ACTION_REPLAY) {
		params.script_file = [runGameParams.commandScriptFileUrl fileSystemRepresentation];
		params.script_quiet = ! runGameParams.echoOutputFromCommandScriptReplay;
	}
		
	if (runGameParams.captureTranscript) {
		params.log_file = [runGameParams.transcriptFileUrl fileSystemRepresentation];
	}
	
	if (runGameParams.dontSeedRandomizer) {
		params.seed_rand = NO;
	}
	
	//TODO ? params.more_mode
	//TODO ? params.log_charset

	//TODO for T2 games too?:
	char *argv[] = {/*"datesave", "restore"*/};
		//TODO dev mode dialog to get these
	int argc = sizeof(argv) / sizeof(char*);
	if (argc >= 1) {
		params.prog_argc = argc;
		params.prog_argv = argv;
	}

	//TODO ? this->fTads3 = true;
	vm_run_image(&params);
	
	[self cleanup];
}

- (void)cleanup
{
	if (_clientifc != nil) {
		delete _clientifc;
		_clientifc = nil;
	}
	if (_hostifc != nil) {
		delete _hostifc;
		_hostifc = nil;
	}
	_t2AppCtx = nil; // ref to singleton
}

@end


//TODO mv to sep C++ / Obj-C++ file:
// like qtads
void
os_init_ui_after_load( class CVmBifTable* /*bif_table*/, class CVmMetaTable* /*meta_table*/)
{
}

//TODO mv to sep C++ / Obj-C++ file:
/* Enable/disable a System Menu Command event in os_get_event().
 */
// TODO? Just a dummy implementation for now.
void
os_enable_cmd_event( int id, unsigned int status)
{
}


