from JascApp import *
from Tkinter import *
import tkFileDialog

#Default values
width = 600
height = 600
compress = 10
	
def ScriptProperties():
	return {
		'Author': u'Neil Moomey',
		'Copyright': u'Neil Moomey',
		'Description': u'Neil\'s Web Photogallery Creator',
		'Host': u'Paint Shop Pro',
		'Host Version': u'8.10'
		}
	
def Do(Environment):
	# EnableOptimizedScriptUndo
	App.Do( Environment, 'EnableOptimizedScriptUndo', {
            
			})
	#Clear window
	App.Do( Environment, 'ScriptWndClear' )
	
	
	# Prompt for max height and width.  
	result = App.Do( Environment, 'GetNumber', {
		'DefaultValue': width,
		'MinValue': 0,
		'MaxValue': 65535,
		'DialogTitle': 'GetNumber - ResizeToLimit',
		'Prompt': 'Select the desired maximum height or width.',
		'GeneralSettings': {
		'ExecutionMode': App.Constants.ExecutionMode.Default
			}
		})
	if not result['OKButton']:
		return
	MaxThumbnailSize = int(result['EnteredNumber'])
	
	# Prompt for compression 
	result = App.Do( Environment, 'GetNumber', {
		'DefaultValue': compress,
		'MinValue': 0,
		'MaxValue': 100,
		'DialogTitle': 'Compression',
		'Prompt': 'Select the desired compression.',
		'GeneralSettings': {
		'ExecutionMode': App.Constants.ExecutionMode.Default
			}
		})
	if not result['OKButton']:
		return
	compression = int(result['EnteredNumber'])
	
	# Prompt for title
	result = App.Do( Environment, 'GetString', {
		'DefaultText': '',
		'DialogTitle': 'Title',
		'Prompt': 'Select the title for your webpage.',
		'MaxLength': 300
		})
	if not result['OKButton']:
		return
	title = str(result['EnteredText'])
	
	HTML_FILE_TYPES=[("htm files","htm"),("All files","*")]
	fileSave=tkFileDialog.asksaveasfilename(filetypes=HTML_FILE_TYPES, title="Select the html file you wish to create.")
	slashPosition = fileSave.rfind('/')
	fileSavePath=fileSave[0:slashPosition]
	print "fileSavePath = " + fileSavePath

	# Start html
	tag = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"
	tag += "<html>\n"
	tag += "<head>\n"
	tag += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n"
	tag += "</head>\n"
	tag += "<body>\n"
	tag += "<table align=\"center\" width=\"" + str(MaxThumbnailSize) + "\">\n"
	tag += "<tr><td align=\"center\">\n"
	tag += "<p><b><font type=\"arial\">" + title + "</font></b></p><br>\n"	
	
	# Create a list for the html tags
	tagList = []
	
	### Start Main Loop ###
	while App.ActiveDocument:
		flag=1		
		
		# Determine new filename
		print'File is: ' + App.ActiveDocument.Title
		filenameWithoutExt=App.ActiveDocument.Title.split(".")[0]
		fname = filenameWithoutExt + '_' + str(MaxThumbnailSize) + '.jpg'
		finalname=fileSavePath + "/" + fname
		
		# compute the width and the height of image, preserving the aspect ratio
		ImageInfo = App.Do( Environment, 'ReturnImageInfo' )
		Width = ImageInfo['Width']
		Height = ImageInfo['Height']
		Title = ImageInfo['Title']		

		if Width <= MaxThumbnailSize and Height <= MaxThumbnailSize:
			print 'Document %s smaller than requested image or the same size' % ( Title )
			NewWidth  = Width
			NewHeight = Height
			flag=0
		elif Width > Height:
			NewWidth  = MaxThumbnailSize
			NewHeight = int(MaxThumbnailSize * float(Height) / float(Width))
		else:   # height > width
			NewHeight = MaxThumbnailSize
			NewWidth  = int(MaxThumbnailSize * float(Width) / float(Height))

		print 'Document %s resized to %d x %d' % ( Title, NewWidth, NewHeight )
        
		if flag==1:
			App.Do( Environment, 'Resize', {
					'CurrentDimensionUnits': App.Constants.UnitsOfMeasure.Pixels, 
					'CurrentResolutionUnits': App.Constants.ResolutionUnits.PixelsPerIn, 
					'MaintainAspectRatio': App.Constants.Boolean.true, 
					'OriginalDimensionUnits': App.Constants.UnitsOfMeasure.Pixels, 
					'OriginalResolutionUnits': App.Constants.ResolutionUnits.PixelsPerIn, 
					'Resample': App.Constants.Boolean.true, 
					'ResampleType': App.Constants.ResampleType.SmartSize, 
					'ResizeAllLayers': App.Constants.Boolean.true, 
					'Resolution': 100.000, 
					'Width': NewWidth, 
					'Height': NewHeight, 
					'GeneralSettings': {
						'ExecutionMode': App.Constants.ExecutionMode.Silent, 
						'AutoActionMode': App.Constants.AutoActionMode.Match
						}
					})
		# Sharpen
		App.Do( Environment, 'Sharpen', {
            
			})

		# NormalViewing
		App.Do( Environment, 'NormalViewing', {
				'GeneralSettings': {
					'ExecutionMode': App.Constants.ExecutionMode.Default, 
					'AutoActionMode': App.Constants.AutoActionMode.Match
					}
				})

		if flag==1:
			# FileSaveAs
			App.Do( Environment, 'FileSaveAs', {
					'Encoding': {
						'JPG': {
							'Variant': App.Constants.JpegFormat.Standard, 
							'CompressionFactor': compression, 
							'ChromaSubSampling': App.Constants.ChromaSubSampling.YCC_2x2_1x1_1x1
							}
						}, 
					'FileName': finalname,
					'FileFormat': App.Constants.FileFormat.JPG, 
					'FormatDesc': u'JPEG - JFIF Compliant', 
					'GeneralSettings': {
						'ExecutionMode': App.Constants.ExecutionMode.Silent, 
						'AutoActionMode': App.Constants.AutoActionMode.Match
						}, 
					'DefaultProperties': []
					})
		# Create HTML
		tagList.append("<img src=\"" + App.ActiveDocument.Title + "\" alt=\"" + filenameWithoutExt + "\" border=\"0\" width=\"" + str(NewWidth) + "\" height=\"" + str(NewHeight) + "\">\n<p></p>\n")					
		
		# FileClose
		App.Do( Environment, 'FileClose', {
				'GeneralSettings': {
					'ExecutionMode': App.Constants.ExecutionMode.Silent, 
					'AutoActionMode': App.Constants.AutoActionMode.Match
					}
				})

	# Sort the list and add it to the html tag variable
	tagList.sort()		
	for x in tagList:
		tag += x
		
	tag += "<p>[<a href=\"/\">Home</a>]</p>\n"
	tag += "</td></tr>\n"
	tag += "</table>\n"
	tag += "</body>\n"
	tag += "</html>"
	print tag
	
	# create file
	output = open(fileSave,'w')
	output.write(tag)




