#!/usr/bin/python

# tz_pil.py
#       --copyright--                   Copyright 2014 (C) Tranzoa, Co. All rights reserved.    Warranty: You're free and on your own here. This code is not necessarily up-to-date or of public quality.
#       --url--                         http://www.tranzoa.net/tzpython/
#       --email--                       pycode is the name to send to. tranzoa.com is the place to send to.
#       --bodstamps--
#       December 28, 2014       bar
#       --eodstamps--
##      \file
#       \namespace              tzpython.tz_pil
#
"""
    Python Imaging Library things.

"""


import  os
import  sys

from PIL    import  Image
from PIL    import  ImageDraw
from PIL    import  ImageFont

import  tzlib
import  replace_file



DEFAULT_FONT_SIZE   = 10        #: note: chosen at random


#
#   Legacy things that should be here now.
#
pil_tostring            = tzlib.pil_tostring
pil_fromstring          = tzlib.pil_fromstring
a_pickleable_pil_image  = tzlib.a_pickleable_pil_image


def get_a_font_at_given_size(sz = None, path_names = None, font_names = None, array_for_file_name = None) :
    """ Return an appropriate font at the given size. Or the default font. Or None. """
    sz  = sz or DEFAULT_FONT_SIZE

    if  array_for_file_name is None :
        array_for_file_name = []
    if  not len(array_for_file_name) :
        array_for_file_name.append('')

    for fn      in (font_names or []) + [ 'DroidSansMono.ttf', 'consola.ttf', 'arial.ttf', 'Ubuntu-R.ttf', ] :
        lfn =   fn.lower()
        for dn  in (path_names or []) + [ os.path.join('..', 'tools', 'fonts'), os.path.join(tzlib.expand_user_vars('~'), '.fonts'), os.path.join('/', 'usr', 'share', 'fonts', 'truetype'), ] :
            if  os.path.isdir(dn) :
                fns = tzlib.ext_ambiguous_file_list(dn, ".ttf", do_sub_dirs = True) + tzlib.ext_ambiguous_file_list(dn, ".TTF", do_sub_dirs = True)
                for ffn in fns :
                    if  os.path.basename(ffn).lower() == lfn :
                        try :
                            array_for_file_name[-1] = ffn

                            return(ImageFont.truetype(ffn, sz))

                        except ( OSError, IOError, ValueError ) :
                            pass
                        try :
                            array_for_file_name[-1] = fn

                            return(ImageFont.truetype(fn, sz))

                        except ( OSError, IOError, ValueError ) :
                            pass
                        pass
                    pass
                pass
            pass
        pass
    try :
        array_for_file_name[-1] = ''

        return(ImageFont.load_default())                    # give up - just give the guy the default font

    except ( OSError, IOError, ValueError ) :
        pass

    return(None)



help_str    = """
%s (options)    ambiguous_image_file_name...

Options:
    --font          name            Try to load the given .ttf font (by base file name - multiple names OK).
    --font_size     size            Set the font size   (default: %u)
    --font_color    color           Set the font color  (default: %s)
    --outdir        directory       Directory to put output images in as the input image file names.
    --output        image_file_name Output file name (for one image).
    --sub_dirs                      Include matching files in subdirectories.

Test.
    Copy the input files to the output directory or file, as appropriate,
    with the file name and font information painted on the output image.

"""

#
#
if __name__ == '__main__' :

    import  TZCommandLineAtFile


    program_name    = sys.argv.pop(0)

    TZCommandLineAtFile.expand_at_sign_command_line_files(sys.argv)

    fonts           = []
    fsize           = 25
    fcolor          = 'red'
    sub_dirs        = False
    ofile_name      = None
    out_dir         = None

    while True :
        oi  = tzlib.array_find(sys.argv, [ "--help", "-h", "-?", "/?", "/h", "/H" ] )
        if  oi < 0 :    break
        del sys.argv[oi]
        print help_str % ( os.path.basename(program_name), fsize, fcolor, )
        sys.exit(254)


    while True :
        oi  = tzlib.array_find(sys.argv, [ "--font", "-f", ] )
        if  oi < 0 :    break
        del sys.argv[oi]
        fn  = sys.argv.pop(oi)
        if  not os.path.splitext(fn)[1] :
            fn += '.ttf'
        fonts.append(fn)

    while True :
        oi  = tzlib.array_find(sys.argv, [ "--font_size", "--size", "--fs", ] )
        if  oi < 0 :    break
        del sys.argv[oi]
        fsize   = int(sys.argv.pop(oi))

    while True :
        oi  = tzlib.array_find(sys.argv, [ "--font_color", "--color", "--fc", ] )
        if  oi < 0 :    break
        del sys.argv[oi]
        fcolor  = sys.argv.pop(oi)


    while True :
        oi  = tzlib.array_find(sys.argv, [ "--sub_dirs", "--subdirs", "--sub-dirs", "--sub_dir", "--subdir", "--sub-dir", "--sd", "-s", ] )
        if  oi < 0 :    break
        del sys.argv[oi]
        sub_dirs    = True                  # search sub-directories


    fnaa    = []
    fnt     = get_a_font_at_given_size(fsize, font_names = fonts, array_for_file_name = fnaa)
    fntname = getattr(fnt, 'getname', lambda : "('Default font', 'PIL')")()
    print "Font name:", fntname, fnaa[-1]

    while len(sys.argv) :
        a   = sys.argv.pop(0)
        if  tzlib.array_find([ "--outdir", ], a) >= 0 :
            outdir      = sys.argv.pop(0)
        elif  tzlib.array_find([ "--output", "-o", ], a) >= 0 :
            ofile_name  = sys.argv.pop(0)
            outdir      = None
        else    :
            fns = tzlib.ambiguous_file_list(a, do_sub_dirs = sub_dirs)
            if  not len(fns) :
                print >>sys.stderr, "No file found: %s!" % a
                sys.exit(111)

            for fn in fns :
                img = Image.open(fn)

                dr  = ImageDraw.Draw(img)
                dr.text(( 5, int(img.size[1] - (fsize or DEFAULT_FONT_SIZE) * 1.5) ), os.path.basename(fn) + ' ' + str(fntname), font = fnt, fill = fcolor or 'red')

                omg = img

                if  ofile_name :
                    ofn = ofile_name
                    if  outdir :
                        if  not os.path.dirname(ofn) :
                            ofn = os.path.join(outdir, ofn)
                        pass
                    pass
                else    :
                    if  not outdir :
                        print >>sys.stderr, "Tell an output name or directory for: %s!" % fn
                        sys.exit(102)

                    ofn = os.path.join(outdir, os.path.basename(fn))
                    if  tzlib.is_same_file(ofn, fn) :
                        print >>sys.stderr, "I won't write over: %s!" % fn
                        sys.exit(103)
                    pass

                obn, ext    = os.path.splitext(ofn)
                tfn         = obn + "_tmp" + ext
                omg.save(tfn)
                replace_file.replace_file(ofn, tfn, ofn + ".bak")

                ofile_name  = None
            pass
        pass

    pass

#
#
#
# eof
