/**
* @file common_itk_util.cpp
* @brief itk warpper utility function 
* @author James
* @history
* ===================================================================================
* Date             Name                   Description of Change
* 18-July-2008     James                  
*/

#pragma warning (disable: 4996) 
#pragma warning (disable: 4819) 


#include <tccore/imantype.hxx>
#include <ae/datasettype.h>
#include <time.h>
#include<tc/tc_macros.h>
#include <tccore/tctype.h>
#include<tccore/workspaceobject.h>
#include "error_handling.h"
#include "common_itk_util.h"

int FindDatasetReferenceExt( tag_t datasettype, const char *datasettype_ref, char ext[10] )
{
	if( datasettype_ref == NULL || ext == NULL )
		return -1;

	strcpy( ext, "" );

	int ref_count = 0, i;
	char **ref_templates = NULL, **ref_formats = NULL;
	ITKCALL( AE_ask_datasettype_file_refs( datasettype, datasettype_ref,
		&ref_count, &ref_templates, &ref_formats ) );
	for( i=0; i<ref_count; i++ )
	{
		if( stricmp( ref_formats[i], "BINARY" ) == 0 )
			break;
	}

	if( i<ref_count )
	{
		strcpy( ext, ref_templates[i] + 2 );
	}

	MEM_free( ref_templates );
	MEM_free( ref_formats );

	return ITK_ok;
}

int CompareDate( date_t date1, date_t date2 )
{
	int comp_ret = 0;
	char str_date1[30] = "";
	char str_date2[30] = "";

	sprintf( str_date1, "%d%2d%2d%2d%2d%2d", date1.year, date1.month, date1.day,
		date1.hour, date1.minute, date1.second );
	sprintf( str_date2, "%d%2d%2d%2d%2d%2d", date2.year, date2.month, date2.day,
		date2.hour, date2.minute, date2.second );

	comp_ret = strcmp( str_date1, str_date2 );
	return comp_ret;
}

int GetRandomTempFile( char tempFile[256] )
{
	time_t now;
	srand( (unsigned)time(&now) );
	struct tm *p = localtime(&now);

	sprintf( tempFile, "TEMP%d%d%d%d%d%d-%d", p->tm_year+1900, p->tm_mon+1,
		p->tm_yday, p->tm_hour, p->tm_min, p->tm_sec, rand() );
	return 0;
}

logical IsItemRevisionType( char object_type[WSO_name_size_c + 1] )
{
	logical is_rev = FALSE;
	
	tag_t cur_type = NULLTAG, parent_type = NULLTAG, temp_type = NULLTAG;
	//ITKCALL( IMANTYPE_find_type( object_type, NULL, &cur_type ) );
	ITKCALL(TCTYPE_find_type(object_type, "", &cur_type));

	parent_type = cur_type;
	temp_type = cur_type;

	do 
	{
		if( cur_type != NULLTAG )
		{
			char* cur_type_name = NULL;
			ITKCALL(TCTYPE_ask_name2( cur_type, &cur_type_name ) );
			//TC8===================
			//if( stricmp( cur_type_name, "ItemRevision" ) == 0 )
			if( strstr( cur_type_name, "Revision" ) != 0 )
			{
				is_rev = TRUE;
				break;
			}
			else {}
		}

		ITKCALL(TCTYPE_ask_parent_type( cur_type, &temp_type ) );
		if( temp_type != NULLTAG )
			parent_type = temp_type;
		cur_type = parent_type;
	} while ( temp_type != NULLTAG );

	return is_rev;
}

