



//	A better version of this script is available at http://aescripts.com/compsfromspreadsheet/




/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////					Templates				/////////////////////////////////////////
////////--------------------------------------------------------------------------------------------------------------//////////|
//																|
//	This script takes the grid from client and uses it to make finished spots using prebuilt templates		|
//																|
//	Grids need to be saved as tab delimeted text files									|
//																|
//------------------------------------------------------------------------------------------------------------------------------|

template		= {};
	VERSION		= 1.0;
	list		= new Array;
	tempSPOT	= {};
	tempGFX		= {};
	order		= {};
	compNum		= 0;
	Length		= 0;
	proj		= app.project.items;
	tc		= "1:0:0" //no frames!
	log		= '';

	run		= 1;

	title		= '';
	market		= '';
	code		= '';
	


////////////////////////////////////////////
//	get template comp id
///////////////////////////////////////


		for(x=1; x<=proj.length; ++x){ // get all comps in project
			if(proj[x].typeName  == 'Composition'){
				if(proj[x].parentFolder.name == 'template SPOTS'){
					tempSPOT[proj[x].name] = proj[x];
				}else if(proj[x].parentFolder.name == 'template GFX'){
					tempGFX[proj[x].name] = proj[x];

				}
			}
		}


///////////////////////////////////////////////////
//get grid and read it.  look at order of columns
//save each entry to list for later processing, alert if template doesn't exist
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	alert("Select the grid file.  Must be converted to tab delemited text");
	grid		= File.openDialog("Select the grid file.  Must be converted to tab delemited text" );
	grid.open("r");

	///////read grid and check for valid template///////
	while(run){
		if(grid.eof){break}
		line = grid.readln();
		if(line){
			line	= line.split("\t");
			if(line[0] && line[1]){
				title		= line[0];
				code		= line[1];
				gfx		= line[2];
				if(tempSPOT[title] && tempGFX[gfx] ){
					entry	= {	"code"		: code,
							"title"		: title,
							"gfx"		: tempGFX[gfx],
							"template"	: tempSPOT[title],
							"len"		: parseInt(tempSPOT[title].duration),
						};
					list.push(entry);
				}else{
					m = "There is no template for\n";
					if(!tempSPOT[title]){
						m += "Spot: "+ title+"\n";
					}
					if(!tempGFX[gfx]){
						m += "Graphics: "+ backpage+"\n";
					}
					alert(m +"Program will terminate");
					run = 0;
					break;
				}
			}
		}
	}


while(run){
	grid.close();


////////////////////////////////////////////////////////////
//	save project as
//	create render folder
//	cycle through all entries and process
/////////////////////////////////////////////////////
	app.project.save();
	alert("Save a new version of the project,\nRenders and log files will be saved to this directory");
	app.project.saveWithDialog();
	path = app.project.file.path;
	Folder(app.project.file.path +'/Renders').create();
	Folder(app.project.file.path +'/Avid Locators').create();

	

	today		=  new Date();
	formatDate	= (today.getMonth()+1) + "/" + today.getDate() + "/" + today.getFullYear();

	for(x=0; x<list.length; ++x){	
		slateC	= list[x]["code"];
		slateT	= list[x]["title"];
		len	= list[x]["len"];


	//make a new comp from template 
		comp = list[x]["template"].duplicate();
		comp.name = ++compNum;

	//enter new data into comp
		comp.layer(1).property("Source Text").setValue(slateT);
		comp.layer(2).property("Source Text").setValue(slateC);
		comp.layer(3).property("Source Text").setValue(formatDate);
		comp.layer(4).property("Source Text").setValue(':30');

	//enter graphic

		comp.layers.add(list[x]["gfx"]);
		comp.layer(1).startTime = 20;

	/////add to renderer
		rq		= app.project.renderQueue.items.add(comp);
		outputModule	= rq.outputModules[1];
		outputModule.applyTemplate("Avid 2:1 RGB lawl");
		outputModule.file = new File(path.toString() + "/Renders/" + comp.name + ".mov");

	///update log and avid locators

		avidLocator();

	//increment timecode
		tcIncrement(len);

	}



	avidFile.close();
	app.project.save();
	run = 0;
}

/////////////////////////////////////////////////////////////////////
//	tapeLog
//   write Data to the tape log
////////////////////////////////////////////////////////////////////

	function tapeLog (string){
		if(Length == 0){
			logFile = new File(path.toString() +'/Tape Logs/log'+tapeNum+ '.txt');
			logFile.open('w');
			logFile.writeln('\t__________________________________________________________________________________________');
			logFile.writeln( '\t| '+ pad('Timecode',15)+'| '+pad('ISCI',11)+'| '+pad('Spot',30)+'| '	  +pad('Length',8)+'| '+pad('Phone Number',14)+' |');
			logFile.writeln('\t|----------------------------------------------------------------------------------------|');
		}
		logFile.writeln(string);
		logFile.writeln('\t|----------------------------------------------------------------------------------------|');
	}


/////////////////////////////////////////////////////////////////////
//	avidLocator
//   write Data for avid locator
////////////////////////////////////////////////////////////////////

	function avidLocator(){
		id	= slateT +' | '+ slateC ;
		frame = (Length * 30) + 300;
		if(Length == 0){
			avidFile = new File(path.toString() +'/Avid Locators/lawl.txt');
			avidFile.open('w');
		}
		avidFile.writeln('lawl\t'+ frame+ '\tV1\tred\t'+ id);
	}
/////////////////////////////////////////////////////////////////////
//	tcDisplay
//   format tc to look like timecode
////////////////////////////////////////////////////////////////////

	function tcDisplay (){
		display = '';

		hours = 1;
		if(Length >= 3600){
			hours += parseInt(Length / 3600);
		}
		if(hours < 10){
			display += '0'+hours+':';
		}else{
			display += hours+':';
		}


		minutes = parseInt(Length / 60) % 60;
		if(minutes < 10){
			display += '0'+minutes+':';
		}else{
			display += minutes+':';
		}

		seconds = Length % 60;
		if(seconds < 10){
			display += '0'+seconds+':00';
		}else{
			display += seconds+':00';
		}


		return display;

	}
/////////////////////////////////////////////////////////////////////
//	tcIncrement
//   take in the length of the current spot, add 60 seconds to it 
//   and increment the Length
////////////////////////////////////////////////////////////////////

	function tcIncrement (spotLength ){
		Length += spotLength;

	}




	function pad (string, padLength){

		rString = '';
		if(string.length > padLength){
			rString = string.substr(0,padLength);
		}else{
			rString = string;
			remain = padLength - string.length;
			for(i = 0; i < remain; ++i){
				rString += ' ';
			}
		}
		return rString;
}