#!/usr/bin/env python

# gallery-blurbed.py 
#  Copyright (C) 2005 Carol Spears
# based on
# cgo-album.py - A Gallery Generator
# Copyright (C) 2003 Manish Singh and Carol Spears
# and
# cgo-camera-gallery.py - A Gallery Generator
# Copyright (C) 2003 Manish Singh and Carol Spears
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.

import os

from gimpfu import *


# The following are html templates. These symbols are valid in them:
#
# album_template:   blurb_class, author
# picture_template: blurb_class, author, artsey_name

blurbedclass_template ="""
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
      "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
  <title>%(blurb_class)s </title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
  <style type="text/css">
    body  {
      background-color:white;
      color:black;
      font-family:sans-serif;
      margin:5%%;
      }
   img {
        border:thin solid black;
	margin:auto;
         }         
   td{
        width:%(thumb_html_width)dpx;
         }         
    p.thumb {
      font-size:80%%;
      }
   ul li  {
     list-style-type:none;
     }
:link{
        text-decoration:none;
         }         
:visited{
        text-decoration:none;
         }         
 :active{
        text-decoration:none;
         }         
 a:hover{
        text-decoration:none;
         }         
  </style>
</head>

<body>
<h1>%(author)s</h1>
<h2>%(blurb_class)s</h2>
<table>
%(table_rows)s
</table>
</body>
</html>
"""


blurbed_template = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
      "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
  <title>%(author)s:%(blurb_class)s:%(blurb_name)s</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
  <style type="text/css">
    body  {
      background-color:white;
      color:black;
      font-family:sans-serif;
      margin:5%%;
      }
   img {
        border:thin solid black;
	margin:auto;
         }         
:link{
        text-decoration:none;
         }         
:visited{
        text-decoration:none;
         }         
 :active{
        text-decoration:none;
         }         
 a:hover{
        text-decoration:none;
         }         
   h3.navigation{
      border:thin solid black;
      text-align:center;
      margin:20px;
      padding:10px;
         }         
  </style>
</head>
<body>
<table>
  <tr><td>
      <h1>%(author)s</h1>
      <h2>%(blurb_class)s</h2>
      <h3>%(blurb_name)s</h3>
      <p>
      %(blurb)s
      </p>
  </td><td>
         <img src="%(image_name)s-screen.jpg" alt="%(blurb_name)s"></img><br></br>
         <p><a href="%(image_name)s-original.jpg">%(original_width)dx%(original_height)d</a></p>
  </td></tr>
</table>
<h3 class="navigation"><a href="%(next_name)s.html">next</a></h3>
<h3 class="navigation"><a href="%(blurb_class)s.html">back to %(blurb_class)s</a></h3>
</body>
</html>
"""
thumb_cell = """
      <td>
         <p class="thumb">
         <a href="%(blurb_name)s.html">%(blurb_name)s</a><br></br>
         <a href="%(blurb_name)s.html">
           <img alt="%(blurb_name)s" src="%(image_name)s-thumb.jpg"></img></a><br></br>
         </p>
      </td>
"""

def write_html(filename, template, info):
    html = open(filename, 'w')
    html.write(template % info)
    html.close()

    # For apache SSI XBitHack
    os.chmod(filename, 0755)


def calc_aspect_dim(dim, orig_dim, other_dim):
    return int(float(dim) / orig_dim * other_dim)


def calc_dims(image, image_info, screen_side, thumb_side):
    original_width = image.width
    original_height = image.height

    if original_width > original_height:
        screen_width = screen_side
        screen_height = calc_aspect_dim(screen_width, original_width, original_height)
        thumb_width = thumb_side
        thumb_height = calc_aspect_dim(thumb_width, original_width, original_height)

    else:
        screen_height = screen_side
        screen_width = calc_aspect_dim(screen_height, original_height, original_width)
        thumb_height = thumb_side
        thumb_width = calc_aspect_dim(thumb_height, original_height, original_width)

    vars = locals()

    for base in ('original', 'screen', 'thumb'):
        for suffix in ('width', 'height'):
            name = '%s_%s' % (base, suffix)
            image_info[name] = vars[name]

def save_jpeg(image, name, comment=""):
    jpeg_save_defaults = (0.75, 0.0, 1, 0, "", 1, 0, 0, 0)
    args = list(jpeg_save_defaults)
    args[4] = comment

    pdb.file_jpeg_save(image, image.active_layer, name, name, *args)

def write_images(page_location, blurbs, common_info, screen_side, thumb_side):

    html_info = []

    for blurb in blurbs:
        info = {'skip': 0} 
        html_info.append(info)

        imagefile = blurb['image_file']
        imagename = blurb['image_name']
        blurbname = blurb['blurb_name']
        yourname = common_info['author']

        print 'imagefile = ' + imagefile

        image = pdb.gimp_file_load(imagefile, imagefile)
        image.flatten()
        calc_dims(image, info, screen_side, thumb_side)

        comment_text = blurbname + 'made by ' + yourname + ' and TheGIMP!'
        comment = "%s\nSource: %s" % (comment_text, imagename)

        original_image = os.path.join(page_location, imagename + '-original.jpg')
        info['original_image'] = original_image
        save_jpeg(image, original_image, comment)

        screen_image = os.path.join(page_location, imagename + '-screen.jpg')
        info['screen_image'] = screen_image
        pdb.gimp_image_scale(image, info['screen_width'], info['screen_height'])
        save_jpeg(image, screen_image, comment)

        thumb_image = os.path.join(page_location, imagename + '-thumb.jpg')
        info['thumb_image'] = thumb_image
        pdb.gimp_image_scale(image, info['thumb_width'], info['thumb_height'])
        save_jpeg(image, thumb_image, comment)

        info['author'] = common_info['author']
        info['blurb_class'] = common_info['blurb_class']
        info['blurb_name'] = blurb['blurb_name']
        info['image_name'] = blurb['image_name']
        info['blurb'] = blurb['text']
        info['next_name'] = blurb['nextname']
        htmlfile = os.path.join(page_location, blurbname + '.html')
        write_html(htmlfile, blurbed_template, info)
        gimp.delete(image)


def write_blurbedclass(page_location, blurbs, common_info, per_row):
    info = common_info.copy()


    table_rows = []

    for i in range(0, len(blurbs), per_row):
        row = []

        for blurb in blurbs[i:i+per_row]:
            row.append(thumb_cell % blurb)

        table_rows.append('<tr>%s</tr>' % ''.join(row))

    info['table_rows'] = '\n'.join(table_rows)

    blurbedclass_page = info['blurb_class'] + '.html'
    htmlfile = os.path.join(page_location, blurbedclass_page)
    write_html(htmlfile, blurbedclass_template, info)

def write_gallery_blurbed_html(author, blurb_class,
                      page_location, blurb_location, 
                      screen_side, thumb_side, per_row):
    blurbs = []
    for filename in os.listdir(blurb_location):
        if not filename.endswith('.blurb'):
            continue

        blurb_file = open(os.path.join(blurb_location, filename))
        blurb_name,blurbext  = os.path.splitext(filename)

        sequence = int(blurb_file.readline())
        image_file = blurb_file.readline().strip()
        text = blurb_file.read()

        imageident,ext  = os.path.splitext(image_file)
        directoryident,image_ident = os.path.split(imageident)
        other,directory_ident = os.path.split(directoryident)
        image_name = directory_ident + '-' + image_ident
        print 'blurb_name = ' +  blurb_name
        print 'image_file = ' +  image_file
        print 'directory_ident = ' +  directory_ident
        print 'image_ident = ' +  image_ident
        print 'image_name = ' +  image_name

        blurb = {}
        blurb['blurb_name'] = blurb_name
        blurb['sequence'] = sequence
        blurb['image_file'] = image_file
        blurb['image_name'] = image_name
        blurb['text'] = text

        blurb_file.close()

        blurbs.append(blurb)

    def sequence_sort(x, y):
        return cmp(x['sequence'], y['sequence'])

    blurbs.sort(sequence_sort)

    for blurb, next in zip(blurbs, blurbs[1:] + blurbs[:1]):
        blurb['nextname'] = next['blurb_name']

    common_info = {'author': author,
                   'blurb_class': blurb_class,
                   'thumb_html_width':thumb_side + 25}

    write_images(page_location, blurbs, common_info, screen_side, thumb_side)
    write_blurbedclass(page_location, blurbs, common_info, per_row)

register(
	"python_fu_gallery_blurbed_html",
	"Makes a specialized html gallery.",
	"Makes a specialized html gallery.",
	"Carol Spears",
	"Carol Spears",
	"2005",
	"<Toolbox>/Xtns/Python-Fu/BlurbedGallery",
	"",
	[
        (PF_STRING, "author", "author Name:", "your name"),
        (PF_STRING, "blurb_class", "Blurb Class", "TastesLikeChicken"),
        (PF_FILE, "page_location", "Where the page should land.", ""),
        (PF_FILE, "blurb_location", "Location of the image blurbs.", ""),
        (PF_INT, "screen_side", "Maximum width or height for screen sized images", 432),
        (PF_INT, "thumb_side", "Maximum width or height for thumbnails", 100),
        (PF_INT, "per_row", "Images per row", 5)
	],
	[],
	write_gallery_blurbed_html)

main()

