#!/usr/bin/env python
#
#   Copyright by Floyd L. Davidson, floyd@apaflo.com
#
#   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 3 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., 675 Mass Ave, Cambridge, MA 02139, USA.

def textlineone():
   return " %D "
#
#     This is the line that I use:
#
#  return "Barrow, Alaska -- %D"

def textlinetwo():
   return "Edit line 27 in file signature.py"
#
#     This is the line that I use:
#
#  return "Copyright %Y Floyd L. Davidson, floyd@apaflo.com"

import os, sys, time, math, string
from gimpfu import *

gettext.install("gimp20-python", gimp.locale_directory, unicode=True)

def python_signature(image, drawable, 
                     deflts, textloc, rotation, 
                     text1, text2,
                     font1, font2, 
                     color1, color2, 
                     size1, size2,
                     x1, y1, x2, y2, 
                     center):
  
  def python_fdate():
    imagefile = "/u2/gimp/gimp/test.png"
    if os.path.isfile(image.name) == True:
      imagefile = os.path.abspath(image.name)

    exif      = "error"
    mypath    = os.path.dirname(imagefile)
    fname     = os.path.basename(imagefile)
    origfname = fname
    extent    = string.lower(fname[1 + fname.rfind(".", 0, -1):])
    ffname    = [ extent, fname[0:fname.find(".", 0, -1)], fname ]

    # Add to the list of files to look for, in the prefered order.
    # The first one found that has a valid "Create Date" is used.
    ffname.append(ffname[1] + ".nef")
    ffname.append(ffname[1] + ".NEF")
    ffname.append(ffname[1] + ".jpg")
    ffname.append(ffname[1] + ".JPG")
    ffname.append(ffname[1] + ".jpeg")
    ffname.append(ffname[1] + ".JPEG")
    ffname.append(ffname[1] + ".tif")
    ffname.append(ffname[1] + ".TIF")
    ffname.append(ffname[1] + ".tiff")
    ffname.append(ffname[1] + ".TIFF")
    ffname.append(ffname[1] + ".ppm")
    ffname.append(ffname[1] + ".PPM")
    ffname.append(ffname[1] + ".ext")
    ffname.append(ffname[1] + ".unknown")

    for a in ffname[2:]:
      fname = a[0:]
      if fname[fname.rfind(".", 0, -1):] == ".ext":
         pattern = '^File\ Modification\ Date/Time'
         fname = origfname
      else:
         pattern = '^Create\ Date'

      path = mypath

      while path != "/":
        imagefile = path + "/" + fname
        try:
          id = open(imagefile)
        except IOError:
          path = os.path.dirname(path)
          continue
        else:
          id.close()
          break
      
      if path == "/":
        continue

      command = "exiftool " + imagefile + " | grep " + pattern

      try:
        po = os.popen(command)
      except IOError:
        print "Error encountered"
        continue

      exif = po.read()

      if exif[0:4] == pattern[1:5]:
        if exif[32:36] == ': 20':
          matched = exif[32:45]
          break
        else:
          continue
      else:
        continue

    if len(exif) != 54:
      return [ "Today", time.localtime(time.time()) ]
    else:
      return [ imagefile, time.strptime(matched, ": %Y:%m:%d ") ]


  #
  #  Convert a string with dates, per the following codes:
  #
  #      %D  to  "January 2, 2000"
  #      %F  to  "2000-01-02"
  #      %d  to the day of the month, unpadded, i.e., 1-31
  #      %p  to the day of the month, padded, i.e., 01-31
  #      %f  to the full path of the file from which data was retrieved
  #      %M  to the name of the month, i.e., January
  #      %m  to the month, 1-12
  #      %Y  to the year, 2000
  #      %y  to the year, 00

  def python_strdated(line):

    line  = string.replace(line, "%%", "This.is.a.percent")

    full0 = time.strftime("%B %-1d, %Y", fdate[1])   # %D
    line  = string.replace(line, "%D", full0)

    full1 = time.strftime("%Y-%m-%d",    fdate[1])   # %F
    line  = string.replace(line, "%F", full1)

    M     = time.strftime("%B",          fdate[1])   # %M
    line  = string.replace(line, "%M", M)

    m     = time.strftime("%m",          fdate[1])   # %m
    line  = string.replace(line, "%m", m)

    d     = time.strftime("%-1d",        fdate[1])   # %d
    line  = string.replace(line, "%d", d)

    p     = time.strftime("%d",          fdate[1])   # %p
    line  = string.replace(line, "%p", p)

    Y     = time.strftime("%Y",          fdate[1])   # %Y
    line  = string.replace(line, "%Y", Y)

    y     = time.strftime("%y",          fdate[1])   # %y
    line  = string.replace(line, "%y", y)

    f     =                              fdate[0]    # %f
    line  = string.replace(line, "%f", f)

    line  = string.replace(line, "This.is.a.percent", "%%")

    return line

  fdate = python_fdate()

  if text1 == "":
      text1 = "."
      size1 = 1

  if text2 == "":
      text2 = "."
      size1 = 1

  text1 = python_strdated(text1)
  text2 = python_strdated(text2)

  image.undo_group_start()

  original_image = image.active_layer

  mode = pdb.gimp_drawable_is_rgb(original_image)

  if mode == False:
      pdb.gimp_image_convert_rgb(image)

  background = gimp.get_background()
  foreground = gimp.get_foreground()

  textlayer1 = gimp.Layer(image, "textlayer1", 
  drawable.width, drawable.height, RGBA_IMAGE, 100, NORMAL_MODE)
  image.add_layer(textlayer1, 0)
  pdb.gimp_drawable_fill(textlayer1, 3)  # transparent fill

  #set the back and foreground colors
  gimp.set_background(255, 255, 255)
  gimp.set_foreground(color1)

  x = 0
  y = 0
  r = 0

  # Disable rotation if location is not Page Center
  if textloc != "pc":
    rotation = 0 

  if rotation != 0:
    r = math.radians(rotation)
    x = image.width  / 4
    y = image.height / 4

  floattext1 = pdb.gimp_text_fontname(image, textlayer1,
     x, y, text1, 0, 1, size1, 1, font1)

  topwidth  = floattext1.width
  topheight = floattext1.height

  if rotation != 0:
    #set the floating selection rotation center on text line 1
    centerx = x + (topwidth  / 2)
    centery = y + (topheight / 2)
    pdb.gimp_drawable_transform_rotate_default(floattext1, r, 0, centerx, centery, 1, 0)

  pdb.gimp_floating_sel_anchor(floattext1)

  gimp.set_background(255,255,255)
  gimp.set_foreground(color2)

  textlayer2 = gimp.Layer(image, "textlayer2", 
     drawable.width, drawable.height, RGBA_IMAGE, 100, NORMAL_MODE)
  image.add_layer(textlayer2, 0)
  pdb.gimp_drawable_fill(textlayer2, 3)  # transparent fill

  floattext2 = pdb.gimp_text_fontname(image, textlayer2,
     x, y, text2, 0, 1, size2, 1, font2)

  botwidth  = floattext2.width
  botheight = floattext2.height

  if rotation != 0:
    #set the floating selection rotation center on text line 2
    centerx = x + (botwidth / 2)
    centery = y + (botheight / 2)
    pdb.gimp_drawable_transform_rotate_default(floattext2, r, 0, centerx, centery, 1, 0)

  pdb.gimp_floating_sel_anchor(floattext2)

  y2 = y2 - 5  # squeeze em together a little

  if textloc == "pc":
    pdb.gimp_layer_set_offsets(textlayer1, x1, y1)
    pdb.gimp_layer_set_offsets(textlayer2, x1 + x2, y1 + y2)

  elif textloc == "ul":
    if botwidth > topwidth:
      x = x1 + ((botwidth - topwidth) / 2)
      y = y1
      pdb.gimp_layer_set_offsets(textlayer1, x, y)
      x = x1
      y = y1 + y2 + topheight
      pdb.gimp_layer_set_offsets(textlayer2, x, y)
    else:
      x = x1
      y = y1
      pdb.gimp_layer_set_offsets(textlayer1, x, y)
      x = x1 + ((topwidth - botwidth) / 2)
      y = y1 + y2 + topheight
      pdb.gimp_layer_set_offsets(textlayer2, x, y)

  elif textloc == "ur":
    if botwidth > topwidth:
      if center == False:
        topwidth = botwidth
      x = image.width - x1 - botwidth + ((botwidth - topwidth)/2)
      y = y1
      pdb.gimp_layer_set_offsets(textlayer1, x, y)
      x = image.width - x1 - botwidth
      y = y1 + y2 + topheight
      pdb.gimp_layer_set_offsets(textlayer2, x, y)
    else:
      if center == False:
        botwidth = topwidth
      x = image.width -x1 - topwidth
      y = y1
      pdb.gimp_layer_set_offsets(textlayer1, x, y)
      x = image.width -x1 - topwidth + ((topwidth - botwidth)/2)
      y = y1 + y2 + topheight
      pdb.gimp_layer_set_offsets(textlayer2, x, y)

  elif textloc == "lr":
    if botwidth > topwidth:
      if center == False:
        topwidth = botwidth
      x = image.width - x1 - botwidth + ((botwidth - topwidth)/2)
      y = image.height - y1 - y2 - topheight - botheight
      pdb.gimp_layer_set_offsets(textlayer1, x, y)
      x = image.width - x1 - botwidth
      y = image.height - y1 - botheight
      pdb.gimp_layer_set_offsets(textlayer2, x, y)
    else:
      if center == False:
        botwidth = topwidth
      x = image.width - x1 - topwidth
      y = image.height - y1 - y2 - topheight - botheight
      pdb.gimp_layer_set_offsets(textlayer1, x, y)
      x = image.width - x1 - topwidth + ((topwidth - botwidth)/2)
      y = image.height - y1 - botheight
      pdb.gimp_layer_set_offsets(textlayer2, x, y)

  elif textloc == "ll":
    if botwidth > topwidth:
      if center == False:
        topwidth = botwidth
      x = x1 + ((botwidth - topwidth) / 2)
      y = image.height - y1 - y2 - topheight - botheight
      pdb.gimp_layer_set_offsets(textlayer1, x, y)
      x = x1
      y = image.height - y1 - botheight
      pdb.gimp_layer_set_offsets(textlayer2, x, y)
    else:
      if center == False:
        botwidth = topwidth
      x = x1
      y = image.height - y1 - y2 - topheight - botheight
      pdb.gimp_layer_set_offsets(textlayer1, x, y)
      x = x1 + ((topwidth - botwidth) / 2)
      y = image.height - y1 - botheight
      pdb.gimp_layer_set_offsets(textlayer2, x, y)

  elif textloc == "uc":
    if botwidth > topwidth:
      x = x1 + ((botwidth - topwidth + image.width - botwidth) / 2)
      y = y1
      pdb.gimp_layer_set_offsets(textlayer1, x, y)
      x = x1 + ((image.width - botwidth) / 2)
      y = y1 + y2 + topheight
      pdb.gimp_layer_set_offsets(textlayer2, x, y)
    else:
      x = x1 + ((image.width - topwidth) / 2)  
      y = y1
      pdb.gimp_layer_set_offsets(textlayer1, x, y)
      x = x1 + ((topwidth - botwidth + image.width - topwidth) / 2)
      y = y1 + y2 + topheight
      pdb.gimp_layer_set_offsets(textlayer2, x, y)

  elif textloc == "lc":
    if botwidth > topwidth:
      if center == False:
        topwidth = botwidth
      x = x1 + ((botwidth - topwidth + image.width - botwidth) / 2)
      y = image.height - y1 - y2 - topheight - botheight
      pdb.gimp_layer_set_offsets(textlayer1, x, y)
      x = x1 + ((image.width - botwidth) / 2)
      y = image.height - y1 - botheight
      pdb.gimp_layer_set_offsets(textlayer2, x, y)
    else:
      if center == False:
        botwidth = topwidth
      x = x1 + ((image.width - topwidth) / 2)
      y = image.height - y1 - y2 - topheight - botheight
      pdb.gimp_layer_set_offsets(textlayer1, x, y)
      x = x1 + ((topwidth - botwidth + image.width - topwidth) / 2)
      y = image.height - y1 - botheight
      pdb.gimp_layer_set_offsets(textlayer2, x, y)

  #hide the new layer
  image.active_layer = original_image

  #reset to original back and foreground
  gimp.set_background(background)
  gimp.set_foreground(foreground)
  gimp.displays_flush()
  image.undo_group_end()

register(
  "python_fu_signature",
  N_("Add signature to photograph"),
  """Adds two line signature, with data and copyright defaults""",
  "Floyd L. Davidson",
  "Floyd L. Davidson",
  "Copyright 2007",
  N_("Signature-1"),
  "*",
  [
  (PF_IMAGE, "image", "Input image", None),
  (PF_DRAWABLE, "drawable", "Input drawable", None),
  (PF_INT,    "deflts",   "Reset Defaults (set 1-5, and exit)", '0'),
  (PF_RADIO,  "textloc",  "Page Location of text",      "lc",
      (("Page Center  (rotate enabled)", "pc"),
       ("Lower Left   (rotate disabled)", "ll"), ("Upper Left   (rotate disabled)", "ul"),
       ("Lower Right  (rotate disabled)", "lr"), ("Upper Right  (rotate disabled)", "ur"),
       ("Lower Center (rotate disabled)", "lc"), ("Upper Center (rotate disabled)", "uc")       
      )),
  (PF_INT,    "rotation", "Rotate Text +/- degrees", '0'),
  (PF_STRING, "text1",    "Custom Text First Line",         textlineone()),
  (PF_STRING, "text2",    "Custom Text Second Line",        textlinetwo()),
  (PF_FONT,   "font1",    "Top Line Font",                  "Sans Bold"),
  (PF_FONT,   "font2",    "Bottom Line Font",               "Sans Bold"),
  (PF_COLOR,  "color1",   "Font Color Top Line",            (0, 20, 20)),
  (PF_COLOR,  "color2",   "Font Color Bottom Line",         (20, 20, 0)),
  (PF_INT,    "size1",    "Font Size Top Line",             '70'),
  (PF_INT,    "size2",    "Font Size Bottom Line",          '12'),
  (PF_INT,    "x1",       "Horz Offset To Near Edge",       '0'), 
  (PF_INT,    "y1",       "Vert Offset To Near Edge",       '15'),
  (PF_INT,    "x2",       "Between Line Horz Spacing",      '0'), 
  (PF_INT,    "y2",       "Between Line Vert Spacing",      '10'),
  (PF_TOGGLE, "center",   "Center Shorter Line",            1)
  ],
  [],
  python_signature,
  menu="/Python-Fu",
  domain=("gimp20-python", gimp.locale_directory)
  )

main()