/**
 * This script is run everytime an album is generated.
 */
import se.datadosen.jalbum.JAFilter;
import se.datadosen.jalbum.event.*;
import se.datadosen.jalbum.*;
import javax.swing.*;
import java.net.*;
import java.io.*;

engine.processBeanShellFile( new File(programDirectory, "includes/printing.bsh") );


//------------------------- Setup Utilities -------------------------
public void setupUtilities()
{
	GeneralUtils.setSkinDirectory( skinDirectory );
	MediaUtils.setSkinDirectory( skinDirectory );
}

//------------------------- Display message -------------------------
public void displayMessage(String msg)
{
    if( window!=null )
        window.messageBox(msg);
    else
        System.out.println(msg);
}

//------------------------- Check for variable definition -------------------------
public void checkVariableDefinition(Object var, String varName)
{
	if( var==void || var.toString().trim().equals("") )
	{
		String msg = "No '" + varName + "' is defined! Operation aborted!";

		displayMessage( msg );
		throw new OperationAbortedException( msg );
	}
}

//------------------------- Check the version -------------------------
public void checkSkinVersion()
{
	String currentVersion = generator.substring( generator.indexOf(' ') + 1 );

	if( currentVersion.compareTo(Constants.MINIMUM_JALBUM_VERSION) < 0 )
	{
		String msg = "This skin actually requires JAlbum " + Constants.MINIMUM_JALBUM_VERSION + ". Please upgrade to the latest version at http://www.jalbum.net";

	    displayMessage( msg );
	    throw new OperationAbortedException( msg );
	}
}

//----------- Figure out if we can integrate with online printing service -----------
public void checkOnlinePrintSupport()
{
	showPrintingWarnings();
}

//----------- Figure out if the priliminaries are there for Remarks feature -----------
private boolean hasRemarksSupport()
{
	return( (includeViewerRemarksOnSlides!=void && includeViewerRemarksOnSlides) || (includeViewerRemarksOnFolders!=void && includeViewerRemarksOnFolders) );
}

public void checkRemarksSupport()
{
	if( !hasRemarksSupport() )
		return;
		
	checkVariableDefinition(remarksDatabaseType, "database type");
	checkVariableDefinition(remarksDatabaseUrl, "database URL");
	checkVariableDefinition(remarksDatabaseName, "database name");
	checkVariableDefinition(remarksDatabaseUserName, "database user name");
	checkVariableDefinition(remarksDatabaseTableName, "database table name");
	checkVariableDefinition(remarksAdminUser, "admin user name");
	checkVariableDefinition(remarksAdminPassword, "admin password");
	checkVariableDefinition(remarksDateFormat, "date format");

	if( remarksUseCaptcha!=void && remarksUseCaptcha )
		checkVariableDefinition(remarksCaptchaDigits, "CAPTCHA digits");

	if( remarksNotifyViaEmail!=void && remarksNotifyViaEmail )
	{
		checkVariableDefinition(remarksNotifyToEmail, "notify-to email");
		checkVariableDefinition(remarksNotifyFromEmail, "notify-from email");
	}

	if( !engine.isWriteUTF8() || !engine.getPageExtension().toLowerCase().equals(".php") )
	{
		String msg;

		msg = "The Remarks features requires that 'Write UTF-8' be specified on the Advanced-Main tab and that '.php' be specified as\n";
		msg += "the page extension on the Advanced-Naming tab! Please make these changes before going on with your album generation.";
		displayMessage( msg );
		//engine.setWriteUTF8( true );
		//engine.setPageExtension( ".php" );
		//window.engine2UI();
	    throw new OperationAbortedException( msg );
	}

	// Generate the connect.php in res/php/connect.php
	File template = new File(skinDirectory, "connect.pht");

	if( template.exists() )
	{
		File dest = new File(rootOutputDirectory, "/res/php/connect.php");

		dest.getParentFile().mkdirs();
		engine.processTemplateFile(template, dest);
	}
}


//----------- Figure out if the ratio fields do not have old format! -----------
public void checkRatios()
{
	if( slidePageThumbnailRatio!=void && slidePageThumbnailRatio!=null && !slidePageThumbnailRatio.toString().trim().equals("") )
	{
		if( slidePageThumbnailRatio>0.0 && slidePageThumbnailRatio<=1.0 )
		{
			engine.getSkinVariables().put( Constants.USER_VAR_SLIDE_PAGE_THUMBNAIL_RATIO, "" + ((int)(slidePageThumbnailRatio*100)) );
			if( window!=null )
				se.datadosen.util.PropertyBinder.syncUI(engine.getSkinVariables(), window.getSkinUI());
		}
	}
}

//----------- Installing the filters -----------
public void installFilters()
{
	if( keepFiltersDefinedOutsideFMTabs==void || !keepFiltersDefinedOutsideFMTabs )
		engine.removeAllFilters();

	installZoomFilter();
	installFixedShapeFilter();
	installGrayScaleFilter();
	installLogoFilter();
	installTextFilter();
	installShadowTextFilter();
	installWatermarkTextFilter();
	installBorderFilter();
}

public void installBorderFilter()
{
	BPPFrameHandler thumbFrame = new BPPFrameHandler(engine, BPPFrameHandler.APPLY_LEVEL_THUMBNAIL);
	BPPFrameHandler slideFrame = new BPPFrameHandler(engine, BPPFrameHandler.APPLY_LEVEL_SLIDE);
	BPPFrameHandler folderBorder = new BPPFrameHandler(engine, BPPFrameHandler.APPLY_LEVEL_FOLDER);
	BPPFrameHandler movieSlideFrame = new BPPFrameHandler(engine, BPPFrameHandler.APPLY_LEVEL_MOVIE_SLIDE);
	LogoFilter logoFilter = new LogoFilter();

	logoFilter.setAlign(LogoFilter.RIGHT_ALIGNMENT);
	logoFilter.setMargin(0);
	logoFilter.setOffset(0);
	logoFilter.setValign(LogoFilter.BOTTOM_ALIGNMENT);
	logoFilter.setVoffset(0);
	
	engine.addFilter( thumbFrame, JAFilter.THUMBNAILS_POSTSCALE_STAGE );
	engine.addFilter( slideFrame, JAFilter.CLOSEUPS_POSTSCALE_STAGE );
	
	album.put( Constants.CACHE_KEY_FOLDER_FRAME_FILTER, folderBorder);
	album.put( Constants.CACHE_KEY_SLIDE_FRAME_FILTER, slideFrame);
	album.put( Constants.CACHE_KEY_THUMBNAIL_FRAME_FILTER, thumbFrame);
	album.put( Constants.CACHE_KEY_MOVIE_SLIDE_FRAME_FILTER, movieSlideFrame);
	album.put( Constants.CACHE_KEY_LOGO_FILTER, logoFilter);
}

public void installZoomFilter()
{
	if( (includeZoomFilterOnThumbnails!=void && includeZoomFilterOnThumbnails) || (includeZoomFilterOnSlides!=void && includeZoomFilterOnSlides) )
	{
		if( includeZoomFilterOnThumbnails )
		{
			ZoomFilter filter = new ZoomFilter();

			if( !(zoomFilterPercentOnThumbnails instanceof String) )
				filter.setZoomPercent(zoomFilterPercentOnThumbnails);
			engine.addFilter( filter, prescaleZoomFilterOnThumbnails ? JAFilter.THUMBNAILS_PRESCALE_STAGE : JAFilter.THUMBNAILS_POSTSCALE_STAGE );
		}

		if( includeZoomFilterOnSlides )
		{
			ZoomFilter filter = new ZoomFilter();

			if( !(zoomFilterPercentOnSlides instanceof String) )
				filter.setZoomPercent(zoomFilterPercentOnSlides);
			engine.addFilter( filter, JAFilter.CLOSEUPS_POSTSCALE_STAGE );
		}
	}
}

public void installFixedShapeFilter()
{
	if( (includeFixedShapeFilterOnThumbnails!=void && includeFixedShapeFilterOnThumbnails) || (includeFixedShapeFilterOnSlides!=void && includeFixedShapeFilterOnSlides) )
	{
		if( includeFixedShapeFilterOnThumbnails )
		{
			FixedShapeFilter filter = new FixedShapeFilter();
			engine.addFilter( filter, prescaleFixedShapeFilterOnThumbnails ? JAFilter.THUMBNAILS_PRESCALE_STAGE : JAFilter.THUMBNAILS_POSTSCALE_STAGE );
		}

		if( includeFixedShapeFilterOnSlides )
		{
			FixedShapeFilter filter = new FixedShapeFilter();
			engine.addFilter( filter, JAFilter.CLOSEUPS_POSTSCALE_STAGE );
		}
	}
}

public void installGrayScaleFilter()
{
	if( (includeGrayScaleFilterOnThumbnails!=void && includeGrayScaleFilterOnThumbnails) || (includeGrayScaleFilterOnSlides!=void && includeGrayScaleFilterOnSlides) )
	{
		if( includeGrayScaleFilterOnThumbnails )
		{
			GrayscaleFilter filter = new GrayscaleFilter();
			engine.addFilter( filter, JAFilter.THUMBNAILS_POSTSCALE_STAGE );
		}

		if( includeGrayScaleFilterOnSlides )
		{
			GrayscaleFilter filter = new GrayscaleFilter();
			engine.addFilter( filter, JAFilter.CLOSEUPS_POSTSCALE_STAGE );
		}
	}
}

public void installLogoFilter()
{
	if( (includeLogoFilterOnThumbnails!=void && includeLogoFilterOnThumbnails) || (includeLogoFilterOnSlides!=void && includeLogoFilterOnSlides) )
	{
		if( includeLogoFilterOnThumbnails )
		{
			LogoFilter filter = new LogoFilter();

			try
			{
				new URL(logoFilterSourceOnThumbnails);
			}
			catch( MalformedURLException e )
			{
				logoFilterSourceOnThumbnails = new File(logoFilterSourceOnThumbnails).toURL().toString();
			}

			filter.setSrc(logoFilterSourceOnThumbnails);
			if( !(logoFilterMarginOnThumbnails instanceof String) )
				filter.setMargin(logoFilterMarginOnThumbnails);
			if( !(logoFilterHorizontalOffsetOnThumbnails instanceof String) )
				filter.setOffset(logoFilterHorizontalOffsetOnThumbnails);
			if( !(logoFilterVerticalOffsetOnThumbnails instanceof String) )
				filter.setVoffset(logoFilterVerticalOffsetOnThumbnails);
			filter.setAlign(logoFilterHorizontalAlignOnThumbnails);
			filter.setValign(logoFilterVerticalAlignOnThumbnails);
			engine.addFilter( filter, prescaleLogoFilterOnThumbnails ? JAFilter.THUMBNAILS_PRESCALE_STAGE : JAFilter.THUMBNAILS_POSTSCALE_STAGE );
		}

		if( includeLogoFilterOnSlides )
		{
			LogoFilter filter = new LogoFilter();

			try
			{
				new URL(logoFilterSourceOnSlides);
			}
			catch( MalformedURLException e )
			{
				logoFilterSourceOnSlides = new File(logoFilterSourceOnSlides).toURL().toString();
			}

			filter.setSrc(logoFilterSourceOnSlides);
			if( !(logoFilterMarginOnSlides instanceof String) )
				filter.setMargin(logoFilterMarginOnSlides);
			if( !(logoFilterHorizontalOffsetOnSlides instanceof String) )
				filter.setOffset(logoFilterHorizontalOffsetOnSlides);
			if( !(logoFilterVerticalOffsetOnSlides instanceof String) )
				filter.setVoffset(logoFilterVerticalOffsetOnSlides);
			filter.setAlign(logoFilterHorizontalAlignOnSlides);
			filter.setValign(logoFilterVerticalAlignOnSlides);
			engine.addFilter( filter, JAFilter.CLOSEUPS_POSTSCALE_STAGE );
		}
	}
}

public void installTextFilter()
{
	if( (includeTextFilterOnThumbnails!=void && includeTextFilterOnThumbnails) || (includeTextFilterOnSlides!=void && includeTextFilterOnSlides) )
	{
		if( includeTextFilterOnThumbnails )
		{
			TextFilter filter = new TextFilter();

			filter.setText(textFilterTextOnThumbnails);
			if( !(textFilterFontSizeOnThumbnails instanceof String) )
				filter.setSize(textFilterFontSizeOnThumbnails);
			filter.setFace(textFilterFontFaceOnThumbnails);
			filter.setStyle(textFilterFontStyleOnThumbnails);
			if( !textFilterColorOnThumbnails.trim().equals("") )
				filter.setColor(textFilterColorOnThumbnails);
			if( !(textFilterMarginOnThumbnails instanceof String) )
				filter.setMargin(textFilterMarginOnThumbnails);
			filter.setAlign(textFilterHorizontalAlignOnThumbnails);
			filter.setValign(textFilterVerticalAlignOnThumbnails);
			filter.setAntialias(textFilterAntiAliasOnThumbnails);
			if( !(textFilterHorizontalOffsetOnThumbnails instanceof String) )
				filter.setOffset(textFilterHorizontalOffsetOnThumbnails);
			if( !(textFilterVerticalOffsetOnThumbnails instanceof String) )
				filter.setVoffset(textFilterVerticalOffsetOnThumbnails);
			engine.addFilter( filter, prescaleTextFilterOnThumbnails ? JAFilter.THUMBNAILS_PRESCALE_STAGE : JAFilter.THUMBNAILS_POSTSCALE_STAGE );
		}

		if( includeTextFilterOnSlides )
		{
			TextFilter filter = new TextFilter();

			filter.setText(textFilterTextOnSlides);
			if( !(textFilterFontSizeOnSlides instanceof String) )
				filter.setSize(textFilterFontSizeOnSlides);
			filter.setFace(textFilterFontFaceOnSlides);
			filter.setStyle(textFilterFontStyleOnSlides);
			if( !textFilterColorOnSlides.trim().equals("") )
				filter.setColor(textFilterColorOnSlides);
			if( !(textFilterMarginOnSlides instanceof String) )
				filter.setMargin(textFilterMarginOnSlides);
			filter.setAlign(textFilterHorizontalAlignOnSlides);
			filter.setValign(textFilterVerticalAlignOnSlides);
			filter.setAntialias(textFilterAntiAliasOnSlides);
			if( !(textFilterHorizontalOffsetOnSlides instanceof String) )
				filter.setOffset(textFilterHorizontalOffsetOnSlides);
			if( !(textFilterVerticalOffsetOnSlides instanceof String) )
				filter.setVoffset(textFilterVerticalOffsetOnSlides);
			engine.addFilter( filter, JAFilter.CLOSEUPS_POSTSCALE_STAGE );
		}
	}
}

public void installShadowTextFilter()
{
	if( (includeShadowTextFilterOnThumbnails!=void && includeShadowTextFilterOnThumbnails) || (includeShadowTextFilterOnSlides!=void && includeShadowTextFilterOnSlides) )
	{
		if( includeShadowTextFilterOnThumbnails )
		{
			ShadowTextFilter filter = new ShadowTextFilter();

			filter.setText(shadowTextFilterTextOnThumbnails);
			if( !(shadowTextFilterFontSizeOnThumbnails instanceof String) )
				filter.setSize(shadowTextFilterFontSizeOnThumbnails);
			filter.setFace(shadowTextFilterFontFaceOnThumbnails);
			filter.setStyle(shadowTextFilterFontStyleOnThumbnails);
			if( !shadowTextFilterTextColorOnThumbnails.trim().equals("") )
				filter.setColor(shadowTextFilterTextColorOnThumbnails);
			if( !(shadowTextFilterMarginOnThumbnails instanceof String) )
				filter.setMargin(shadowTextFilterMarginOnThumbnails);
			filter.setAlign(shadowTextFilterHorizontalAlignOnThumbnails);
			filter.setValign(shadowTextFilterVerticalAlignOnThumbnails);
			filter.setAntialias(shadowTextFilterAntiAliasOnThumbnails);
			if( !(shadowTextFilterHorizontalOffsetOnThumbnails instanceof String) )
				filter.setOffset(shadowTextFilterHorizontalOffsetOnThumbnails);
			if( !(shadowTextFilterVerticalOffsetOnThumbnails instanceof String) )
				filter.setVoffset(shadowTextFilterVerticalOffsetOnThumbnails);
			if( !shadowTextFilterShadowColorOnThumbnails.trim().equals("") )
				filter.setShadowColor(shadowTextFilterShadowColorOnThumbnails);
			if( !(shadowTextFilterShadowDistanceOnThumbnails instanceof String) )
				filter.setShadowDistance(shadowTextFilterShadowDistanceOnThumbnails);
			engine.addFilter( filter, prescaleShadowTextFilterOnThumbnails ? JAFilter.THUMBNAILS_PRESCALE_STAGE : JAFilter.THUMBNAILS_POSTSCALE_STAGE );
		}

		if( includeShadowTextFilterOnSlides )
		{
			ShadowTextFilter filter = new ShadowTextFilter();

			filter.setText(shadowTextFilterTextOnSlides);
			if( !(shadowTextFilterFontSizeOnSlides instanceof String) )
				filter.setSize(shadowTextFilterFontSizeOnSlides);
			filter.setFace(shadowTextFilterFontFaceOnSlides);
			filter.setStyle(shadowTextFilterFontStyleOnSlides);
			if( !shadowTextFilterTextColorOnSlides.trim().equals("") )
				filter.setColor(shadowTextFilterTextColorOnSlides);
			if( !(shadowTextFilterMarginOnSlides instanceof String) )
				filter.setMargin(shadowTextFilterMarginOnSlides);
			filter.setAlign(shadowTextFilterHorizontalAlignOnSlides);
			filter.setValign(shadowTextFilterVerticalAlignOnSlides);
			filter.setAntialias(shadowTextFilterAntiAliasOnSlides);
			if( !(shadowTextFilterHorizontalOffsetOnSlides instanceof String) )
				filter.setOffset(shadowTextFilterHorizontalOffsetOnSlides);
			if( !(shadowTextFilterVerticalOffsetOnSlides instanceof String) )
				filter.setVoffset(shadowTextFilterVerticalOffsetOnSlides);
			if( !shadowTextFilterShadowColorOnSlides.trim().equals("") )
				filter.setShadowColor(shadowTextFilterShadowColorOnSlides);
			if( !(shadowTextFilterShadowDistanceOnSlides instanceof String) )
				filter.setShadowDistance(shadowTextFilterShadowDistanceOnSlides);
			engine.addFilter( filter, JAFilter.CLOSEUPS_POSTSCALE_STAGE );
		}
	}
}

public void installWatermarkTextFilter()
{
	if( (includeWatermarkTextFilterOnThumbnails!=void && includeWatermarkTextFilterOnThumbnails) || (includeWatermarkTextFilterOnSlides!=void && includeWatermarkTextFilterOnSlides) )
	{
		if( includeWatermarkTextFilterOnThumbnails )
		{
			WatermarkFilter filter = new WatermarkFilter();

			filter.setText(watermarkTextFilterTextOnThumbnails);
			if( !(watermarkTextFilterFontSizeOnThumbnails instanceof String) )
				filter.setSize(watermarkTextFilterFontSizeOnThumbnails);
			filter.setFace(watermarkTextFilterFontFaceOnThumbnails);
			filter.setStyle(watermarkTextFilterFontStyleOnThumbnails);
			if( !watermarkTextFilterColorOnThumbnails.trim().equals("") )
				filter.setColor(watermarkTextFilterColorOnThumbnails);
			if( !(watermarkTextFilterMarginOnThumbnails instanceof String) )
				filter.setMargin(watermarkTextFilterMarginOnThumbnails);
			filter.setAlign(watermarkTextFilterHorizontalAlignOnThumbnails);
			filter.setValign(watermarkTextFilterVerticalAlignOnThumbnails);
			filter.setAntialias(watermarkTextFilterAntiAliasOnThumbnails);
			if( !(watermarkTextFilterHorizontalOffsetOnThumbnails instanceof String) )
				filter.setOffset(watermarkTextFilterHorizontalOffsetOnThumbnails);
			if( !(watermarkTextFilterVerticalOffsetOnThumbnails instanceof String) )
				filter.setVoffset(watermarkTextFilterVerticalOffsetOnThumbnails);
			if( !(watermarkTextFilterStrengthPercentOnThumbnails instanceof String) )
				filter.setStrengthPercent(watermarkTextFilterStrengthPercentOnThumbnails);
			engine.addFilter( filter, prescaleWatermarkTextFilterOnThumbnails ? JAFilter.THUMBNAILS_PRESCALE_STAGE : JAFilter.THUMBNAILS_POSTSCALE_STAGE );
		}

		if( includeWatermarkTextFilterOnSlides )
		{
			WatermarkFilter filter = new WatermarkFilter();

			filter.setText(watermarkTextFilterTextOnSlides);
			if( !(watermarkTextFilterFontSizeOnSlides instanceof String) )
				filter.setSize(watermarkTextFilterFontSizeOnSlides);
			filter.setFace(watermarkTextFilterFontFaceOnSlides);
			filter.setStyle(watermarkTextFilterFontStyleOnSlides);
			if( !watermarkTextFilterColorOnSlides.trim().equals("") )
				filter.setColor(watermarkTextFilterColorOnSlides);
			if( !(watermarkTextFilterMarginOnSlides instanceof String) )
				filter.setMargin(watermarkTextFilterMarginOnSlides);
			filter.setAlign(watermarkTextFilterHorizontalAlignOnSlides);
			filter.setValign(watermarkTextFilterVerticalAlignOnSlides);
			filter.setAntialias(watermarkTextFilterAntiAliasOnSlides);
			if( !(watermarkTextFilterHorizontalOffsetOnSlides instanceof String) )
				filter.setOffset(watermarkTextFilterHorizontalOffsetOnSlides);
			if( !(watermarkTextFilterVerticalOffsetOnSlides instanceof String) )
				filter.setVoffset(watermarkTextFilterVerticalOffsetOnSlides);
			if( !(watermarkTextFilterStrengthPercentOnSlides instanceof String) )
				filter.setStrengthPercent(watermarkTextFilterStrengthPercentOnSlides);
			engine.addFilter( filter, JAFilter.CLOSEUPS_POSTSCALE_STAGE );
		}
	}
}


//------------------------- Cleanup tasks -------------------------
public void setupCleanupTasks()
{
    if( window==null )
        return;

	window.addJAlbumListener(new JAlbumAdapter() {
		public void albumCreationFinished(JAlbumEvent e) {
			if( !engine.isUpdatedDirsOnly() )
			{
				removeExtraResources(Constants.CACHE_KEY_USED_ICON_SETS, "/res" + Constants.SKIN_ACTION_RESOURCE_DIR, true);
				removeExtraResources(Constants.CACHE_KEY_USED_STYLES, "/res/styles", true);
				removeExtraResources(Constants.CACHE_KEY_USED_FULL_STYLES, "/res/styles", false);
			}

			if( !hasRemarksSupport() )
				deleteDirectory(new File(rootOutputDirectory, "/res/php"));
			window.removeJAlbumListener(this);
			engine.removeAllFilters();
		}

		public void skinChanged(JAlbumEvent e) {
			window.removeJAlbumListener(this);
			engine.removeAllFilters();
		}
	});
}

public void removeExtraResources(String usedResourcesKey, String resourceDirectory, boolean isDirectory)
{
	if( !album.containsKey(usedResourcesKey) )
		return;

	File[] resources = new File(rootOutputDirectory, resourceDirectory).listFiles();
	List usedResources = (List) album.get(usedResourcesKey);

	for( int i=0; i<resources.length; i++ )
	{
		if( isDirectory==resources[i].isDirectory() && !usedResources.contains(resources[i].getName()) )
			deleteDirectory( resources[i] );
	}
}

public void deleteDirectory(File dir)
{
	if( !dir.isDirectory() )
	{
		dir.delete();
		return;
	}

	File[] children = dir.listFiles();

	for( int i=0; i<children.length; i++ )
		deleteDirectory(children[i]);

	dir.delete();
}


//------------------------- Main -------------------------
setupUtilities();
checkSkinVersion();
checkOnlinePrintSupport();
checkRemarksSupport();
checkRatios();
installFilters();
setupCleanupTasks();
