#!/usr/bin/python

# jpeg_tse_commenter.py
#       --copyright--                   Copyright 2019 (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--
#       June 7, 2019            bar
#       June 9, 2019            bar     --no_gps
#                                       --show_date
#       June 30, 2019           bar     TZCommandLineAtFile
#       --eodstamps--
##      \file
#       \namespace              tzpython.jpeg_tse_commenter
#
#
"""
jpeg_tse_commenter.py   (options)   directory_containing_JPEG_images

  Options:

    --create            Make sure there is a .txt file for each JPEG
                        image in the given directory.

    --no_gps            Only create .txt files for images with no GPS info.
                        Implies --create.

  Show the image for which a TSE bash session is editing the .txt file.

  Note: The file being editted by TSE is detected using the wmctrl program.

"""

import  glob
import  os
import  re
import  sys
import  time

import  cv2
import  numpy

import  tzlib
import  tz_jpg


def oops(err_msg) :
    sys.stderr.write(err_msg + "\n")
    sys.exit(1)


TSE_bash_title_re   = re.compile(r"^0x[0-9a-f]+\s+-?\d+\s+\S+\s+(.*)? - TSE Pro$", re.MULTILINE)
JPEG_EXTS           = [ 'jpg', 'jpeg', 'JPG', 'JPEG', ]

WINDOW_NAME         = "jpeg_tse_commenter"


if  __name__ == '__main__' :
    import  TZCommandLineAtFile

    program_name        = os.path.basename(sys.argv[0] or __file__ or __doc__.split()[0])

    TZCommandLineAtFile.expand_at_sign_command_line_files(sys.argv)

    if  len(sys.argv)  <= 1 :
        sys.argv.append("-h")

    if  tzlib.array_find([ a.lower() for a in sys.argv ], [ "--help", "/help", "-h", "-?", "/?", "-?", "/h", ] ) >= 0 :
        ds  = re.sub(r'^(\s*)(\S+)', r'\1' + program_name, __doc__)
        print ds
        sys.exit(0)                         # well, there goes my 254 :)

    create_txt_files        = False
    no_gps                  = False
    show_date               = False

    while True :
        oi  = tzlib.find_argi_and_del(sys.argv, [ "--create", "-c", ])
        if  oi < 0 :
            break
        create_txt_files    = True

    while True :
        oi  = tzlib.find_argi_and_del(sys.argv, [ "--no_gps", ])
        if  oi < 0 :
            break
        no_gps              = True
        create_txt_files    = True

    while True :
        oi  = tzlib.find_argi_and_del(sys.argv, [ "--show_date", "--show_when", ])
        if  oi < 0 :
            break
        show_date           = True


    if  len(sys.argv) > 2   :
        oops("Just tell me the directory to work with!")

    dn  = sys.argv.pop(1)

    if  not os.path.isdir(dn) :
        oops(dn + " is not a directory!")

    fns = []
    for ext in JPEG_EXTS :
        fns    += glob.glob(os.path.join(dn, "*." + ext))
    fns = [ os.path.basename(fn)                                                 for fn in fns if not os.path.basename(fn).startswith('_') ]
    bns = [ os.path.splitext(fn)[0] + "_" + os.path.splitext(fn)[1][1:] + ".txt" for fn in fns ]

    if  create_txt_files :
        for fi, bfn in enumerate(bns) :
            tfn = os.path.join(dn, bfn)
            if  not os.path.exists(tfn) :
                gps             = False
                if  no_gps      :
                    jpg         = tz_jpg.a_jpg(fns[fi])
                    if  jpg     :
                        exif    = jpg.get_exif()
                        if  exif :
                            gps = (exif.get_latitude() != None) or (exif.get_longitude() != None)
                        pass
                    pass
                if  not gps     :
                    print "making", tfn
                    tzlib.write_whole_binary_file(tfn, "")
                pass
            pass
        pass

    blank       = numpy.ones(( 100, 800, 3 ), numpy.uint8) * 255
    cv2.putText(blank, "Not editing an image's comment.", ( 10, 50 ), cv2.FONT_HERSHEY_PLAIN, 1.0, ( 0, 0, 0 ), 1, cv2.LINE_AA)

    showing     = " no such file name "
    while True  :
        r, rs   = tzlib.run_program('wmctrl -l')
        if  r   :
            oops("Cannot run wmctrl: %d:%s\n" % ( r, rs, ))

        tses        = TSE_bash_title_re.findall(rs)
        tses        = [ fn for fn in tses if os.path.splitext(fn)[1] == ".txt" ]

        edit_fns    = [ fn for fn in tses if tzlib.array_find(bns, fn) >= 0 ]
        if  len(edit_fns) == 1 :
            fn          = re.sub(r"_(" + "|".join(JPEG_EXTS) + r")\.txt", r".\1", edit_fns[0])
            if  showing != fn :
                showing = fn
                print   fn
                img     = cv2.imread(fn)
                bg      = max(img.shape)
                if  bg  > 800 :
                    scl = 800.0 / bg
                    img = cv2.resize(img, ( int(img.shape[1] * scl), int(img.shape[0] * scl) ), interpolation = cv2.INTER_AREA)
                if  show_date :
                    jpg = tz_jpg.a_jpg(fn)
                    dt  = jpg.picture_taken_time(dflt = os.path.getmtime(fn))
                    if  dt  > 0 :
                        ds  = time.strftime("%x", time.localtime(dt))
                        cv2.putText(img, ds, ( 10, img.shape[0] - 20 ), cv2.FONT_HERSHEY_PLAIN, 1.0, ( 0,    0,    0    ), 2, cv2.LINE_AA)
                        cv2.putText(img, ds, ( 10, img.shape[0] - 20 ), cv2.FONT_HERSHEY_PLAIN, 1.0, ( 0xff, 0xff, 0xff ), 1, cv2.LINE_AA)
                    pass
                cv2.imshow(WINDOW_NAME, img)
            pass
        elif showing    :
            showing     = ""
            # cv2.destroyWindow(WINDOW_NAME)
            cv2.imshow(WINDOW_NAME, blank)

        k       = cv2.waitKey(2)
        if  k  >= 0 :
            if  k  in [ ord('q'), ord('Q'), ord('x'), ord('X'), 27, ] :
                break
            pass

        time.sleep(.11)
    pass


# eof
