// TDR_auto.cp
// Multifile processing for D&D start
#include <complex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <Strings.h>
#include <math.h>

#include "CustomFileDialog.h"
#include "debugs.h"
#include "inputdialog.h"
#include "datautils.h"
#include "showlist.h"
#include "TDR.h"

DateTimeRec prefs_dtr, dfile_dtr;

static Boolean TDR_IsPrefsNewer(DateTimeRec *prefs_dtr, DateTimeRec *dtr);

static char TI_Format[256];

// top routine of multifile processing
// call from AEHandleOpenDocument
short TDR_AutomaticFT(FSSpec *odoc_fss, long odoc_count)
{
	long i;
	short oldparms_ok = false;
	short alrt;
	Handle dh;
	Str255 tmpstr;
	DateTimeRec Crdtr;
	
	// load current settings
	if(TDR_ReadEnv(&tdrenv) == -1){ 	// no preference
		showstop("\pCannot open Preference File : TDRpreference", 
				"\pPlase set parameters and save it.","\p","\p");
		return -1;
	}
	// get creation date of preference file
	TDR_GetPrefsDate(&prefs_dtr);
	
	// get time interval format from resource fork
	dh = Get1Resource(EDTI_RESTYPE, TDR_EDTI_START_ID + TDR_EDTI_N_TINTERVAL);
	BlockMoveData((**(EdtIHandle)dh).format, tmpstr, (Size)((**(EdtIHandle)dh).format[0] + 1));
	strcpy(TI_Format, PtoCstr(tmpstr));


	for(i = 0 ; i < odoc_count ; i++){
		// Is preference file newer than data file?
		if(oldparms_ok == false){
			GetFileDateTime(*(odoc_fss + i), &dfile_dtr, &Crdtr);
			if(TDR_IsPrefsNewer(&prefs_dtr, &dfile_dtr) == false){ // prefs file is old.
				ParamText("\pThe TDR preference file is older than data file.",
						"\pDo you want to continue processing with old parameters?","\p","\p");
				alrt = CautionAlert(TDR_ALERT_CREATION_DATE, NULL);
				if(alrt == 2){	// continue processing
					oldparms_ok = true;
				}
				else{	// stop processing
					return -1;
				}
			}
		}
	
		if(TDR_Process1File(*(odoc_fss + i)) != 0){
			return -1;
		}
	}
	
	//save environment. save sartnum, etc....
//	TDR_WriteEnv(&tdrenv);

	return 0;
}

short TDR_Process1File(FSSpec odoc_fss)
{
	FInfo fndrInfo;
	FSSpec outfss;
	char outname[128];
	double time_interval;
	Str255 datestr, timestr;
	unsigned long secs;
	char time_interval_str[256], tdrparam_dt_str[256];

	current_fss = &(odoc_fss);  // for displaying file name.

	if(TDR_ReadPrefs(&tdrparam) != 0){   // read preference
		showstop("\pCannot open Preference File : TDRpreference", "\p","\p","\p");
		return -1;
	}
	tdrparam.launch_flag = LAUNCH_BY_DD;
	time_interval = tdrparam.dt;	// save current time interval

	FSpGetFInfo(&odoc_fss, &fndrInfo);
	
	tdrparam.flag_dfile1 = tdrenv.input_ftype;
	tdrparam.fs_dfile1.fss = odoc_fss;
	tdrparam.fs_dfile1.sfr.sfGood = true;
	
	if(TDR_readDatafile(&tdrparam) != 0){	// 読み込む
		return -1;
	} 

	// 表示桁までの比較で十分であると仮定
	sprintf(time_interval_str, TI_Format, time_interval);
	sprintf(tdrparam_dt_str, TI_Format, tdrparam.dt);
	if(strcmp(time_interval_str, tdrparam_dt_str) != 0){
		showstop("\pSampling interval of your data file is not equal to current settings. Cannot continue processing.", 
		         "\p","\p","\p");
		return -1;
	}

	//Make output file name. Name is depends on Environments
	if(strlen(tdrenv.spfile_basename) != 0 && tdrenv.spfile_startnum >= 0){
		sprintf(outname, "%s%d", tdrenv.spfile_basename, tdrenv.spfile_startnum);
		tdrenv.spfile_startnum++;
	}
	else{
		strcpy(outname, PtoCstr(odoc_fss.name));
		strcat(outname, ".eps");
	}
	FSMakeFSSpec(odoc_fss.vRefNum, odoc_fss.parID, CtoPstr(outname), &outfss);
	tdrparam.fs_spec.fss = outfss;
	tdrparam.fs_spec.sfr.sfGood = true;
	
	tdrparam.gC = 0.0; /* cannot set dc value */
	
	// start calculation
	FlushEvents(everyEvent, 0);
	
	/* get processing start time */
	GetDateTime(&secs);
	IUDateString(secs, abbrevDate, datestr);
	IUTimeString(secs, true, timestr);
	strcpy(oinfo.processing_time, PtoCstr(datestr));
	strcat(oinfo.processing_time, PtoCstr(timestr));

	if(StartCalc(&tdrparam) == 0){			/* success! */
		if(tdrenv.output_ftype == TDR_FSFLAG_IGOR){
			saveSpectrIgorWave(&tdrparam);
		}
		else if(tdrenv.output_ftype == TDR_FSFLAG_TEXT){	
			saveSpectrDelimitedText(&tdrparam);
		}
	
		TDR_SaveParmsToResouce(&(tdrparam.fs_dfile1.fss), &tdrparam);
	}
	return 0;
}

// if preference file is newer than data file, return true.
// else return false
static Boolean TDR_IsPrefsNewer(DateTimeRec *prefs_dtr, DateTimeRec *dtr)
{
	unsigned long prefs_sec, dtr_sec;
	
	DateToSeconds(prefs_dtr, &prefs_sec);
	DateToSeconds(dtr, &dtr_sec);
	
	if(prefs_sec < dtr_sec) return false;
	else return true;
}
	
	

