#!/usr/bin/python

# wordpress_header_images.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--
#       October 15, 2014        bar
#       October 16, 2014        bar     --only_new
#       August 11, 2020         bar     use --verbose
#       --eodstamps--
##      \file
#       \namespace              tzpython.wordpress_header_images
#
#
"""
        Find and convert images to be ok for the Wordpress TwentyEleven theme's use.

"""

import  os
import  sys
import  time

from    PIL     import  Image

import  tzlib


WIDTH       = 1000
HITE        = 288

MIN_WIDTH   = WIDTH
MIN_HITE    = HITE


ASPECT_TOLORANCE    = 0.4


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

    Finds in the given files images suitable for Wordpress TwentyEleven theme use,
    and, if an output directory is given, converts them to the proper aspect ratio.

Options:

    --out_dir           directory_name      Set the output directory name.
    --only_new                              Don't replace existing files in the out_dir.
    --tolorance         number              How far from the desired aspect ratio
                                            of %.2f can images be?      default: %f
    --verbose                               Increase the verbosity level.
                                              +1 prints how the image's tolorance value.
                                              +2 prints the image file's date/time.

This program finds and converts image files so that they can be used by the Wordpress
TwentyEleven theme.

Specifically, they must be big enough and near the appropriate aspect ratio.

We're talking %ux%u pixels.


"""



if  __name__ == '__main__' :

    import  TZCommandLineAtFile


    program_name    = sys.argv.pop(0)

    TZCommandLineAtFile.expand_at_sign_command_line_files(sys.argv)


    tolorance       = ASPECT_TOLORANCE
    out_dir         = None
    only_new        = False
    verbose         = 0

    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), WIDTH / float(HITE), tolorance, WIDTH, HITE, )
        sys.exit(254)


    while True :
        oi  = tzlib.array_find(sys.argv, [ "--verbose", "-v", ] )
        if  oi < 0  :   break
        del sys.argv[oi]
        verbose    += 1

    while True :
        oi  = tzlib.array_find(sys.argv, [ "--out_dir", "--out-dir", "--outdir", "-o", ] )
        if  oi < 0  :   break
        del sys.argv[oi]
        out_dir     = sys.argv.pop(oi)

    while True :
        oi  = tzlib.array_find(sys.argv, [ "--only_new", "--only-new", "--onlynew", ] )
        if  oi < 0  :   break
        del sys.argv[oi]
        only_new    = True

    while True :
        oi  = tzlib.array_find(sys.argv, [ "--tolorance", "-t", ] )
        if  oi < 0  :   break
        del sys.argv[oi]
        tolorance   = float(sys.argv.pop(oi))


    fns = []
    while len(sys.argv) :
        afn     = sys.argv.pop(0)
        fns    += tzlib.ambiguous_file_list(afn)
    fns = tzlib.without_dupes(fns)
    fns.sort(lambda a, b : cmp(a.lower(), b.lower()))

    if  not len(fns) :
        print "Tell me files to convert"
        sys.exit(101)

    fns.sort(lambda a, b : cmp(a.lower(), b.lower()))


    if  out_dir :
        out_dir = os.path.abspath(out_dir)

    cnt     = 0
    for fn in fns :
        img = Image.open(fn)
        v   = abs(img.size[0] / float(img.size[1]) - WIDTH / float(HITE))
        if  (img.size[0] >= MIN_WIDTH) and (img.size[1] >= MIN_HITE) and (v < tolorance) :
            if  verbose :
                print "%5.3f" % v,
            if  verbose > 1 :
                print time.strftime("%Y_%m_%d_%H-%M-%S", time.localtime(os.path.getmtime(fn))),
            print fn
            if  out_dir :
                if  os.path.dirname(os.path.abspath(fn)) == out_dir :
                    print "Output directory name is the same as that of %s!" % fn
                    sys.exit(101)
                ofn = os.path.join(out_dir, os.path.basename(fn))
                ofn = os.path.splitext(ofn)[0] + ".jpg"
                if  (not only_new) or (not os.path.isfile(ofn)) :
                    img = img.resize((WIDTH, HITE), Image.ANTIALIAS)
                    img.save(ofn)
                    os.utime(ofn, ( os.path.getatime(fn), os.path.getmtime(fn) ))
                    print "  ", ofn
                pass
            cnt    += 1
        pass
    print cnt, "images found of", len(fns), "images."

#
#
# eof
