# Generate HTML demonstrations based on Screenshots Tool and PngWalkTool QC facility.  
# The screenshots tool is run, creating a sequence of screenshots.  This should be trimmed
# automatically, so that all images are of the same size, and as small as possible.  
# The PNGWalk QC tool is turned on, and then "OK/green" images are written to HTML with 
# the last comment as the caption to each figure.

from javax.xml.parsers import ParserConfigurationException
from javax.xml.parsers import DocumentBuilderFactory
from javax.xml.xpath import XPath
from javax.xml.xpath import XPathExpressionException
from javax.xml.xpath import XPathFactory
from javax.xml.xpath import XPathConstants
from org.xml.sax import InputSource
from java.io import File
from java.io import FileInputStream
from org.virbo.autoplot import AutoplotUtil
from javax.swing import BoxLayout,JPanel,JLabel,JButton,JOptionPane

print '====='
print params 
print '====='

d= getParam('dir','/tmp/pngwalk/', 'the pngwalk home' )
outdir= getParam('outdir','', 'the output directory' )
qconly= getParam('qconly','F', 'only qc records', ['T','F'] )


if ( outdir=='' ): outdir= d

ff= getParam('name', '', 'prefix for each file, e.g. product')

summary= getParam('summary','', 'One-line summary or title' )

if ( d.startswith('file:') ): d= d[5:]

if ( not d.startswith('/') ): raise Exception('folder must start with /')
 
def getCaption( qcFile ):
    'return the last review comment in the xml file'
    print 'qcFile: ', qcFile    
    try:
        myin= FileInputStream( qcFile )
        builder = DocumentBuilderFactory.newInstance().newDocumentBuilder()
        source = InputSource( myin )
        initialDocument = builder.parse(source)    
        factory= XPathFactory.newInstance()
        xpath= factory.newXPath()
        caption= xpath.evaluate( '/qualityControlRecord/reviewComment[last()]/text()', initialDocument, XPathConstants.STRING )
        print 'caption: ', caption
        return caption
    except:
        return 'No Caption'

print 'ls '+d + '/' + ff + '*.png'
ll= listDirectory( d + '/' + ff + '*.png' )

print 'found %d files.'%len(ll)

thedate= TimeParser.create('$Y$m$d_$H$M').format(TimeUtil.now())

if ( ff=='' ): ff= thedate

if ( len(summary)>0 ):
    summary= '<br>' + summary 
    
html= open( outdir + '/' + ff + '.html', 'w' )
html.write( '''
	<head><title>%(dat)s</title></head>
	<body style="background-color: #6B6B6B; margin=0;">
		<div style="padding:20px; top: 0px; margin-right=0px; background-color:black; color:white;height:30px;">
			<strong>%(dat)s</strong>%(summary)s
		</div>
		<div style="background-color: #6B6B6B;margin-left:100px;">
''' % { 'dat':thedate, 'summary':summary } )

for l in ll:
    cap= getCaption( d + '/' + l + '.ok' ) 
    if ( cap=='No Caption' ):
        cap= getCaption( d + '/' + l + '.problem' ) 
    if ( cap=='No Caption' ):
        if ( qconly=='T' ): 
           continue
        else:
           cap= ''

    img= l # remove the '.ok'
    
    html.write( '''<figure style="width:700px; float:left;">
				<a href="%(img)s">
				<img src="%(img)s" style="width:100%%;margin-left:10px;margin-bottom:10px;"></a>
				<figcaption style="color: white; text-align:left;">%(cap)s</figcaption>
			</figure>''' % { 'img':img, 'cap':cap } )

html.write( '''</div>
	</body>
</html>''' )

html.close()

url= outdir+'/' + ff + '.html'
print 'wrote '+url + '.'

msg= 'Wrote '+ url +'.'

panel= JPanel()
panel.setLayout( BoxLayout(panel,BoxLayout.Y_AXIS ))
panel.add( JLabel(msg) )
panel.add( JButton( 'Open in Browser', actionPerformed=lambda a: AutoplotUtil.openBrowser(url) ) )

JOptionPane.showMessageDialog( getViewWindow(),panel)
