#!/usr/bin/env python
#

"""
gimage: graphterm-aware image display
"""

import mimetypes
import os
import sys
import tty
import termios

from optparse import OptionParser

import gtermapi

Work_dir = os.getcwd()

usage = "usage: %prog [-f] <location>"
parser = OptionParser(usage=usage)
parser.add_option("-b", "--blobs",
                  action="store_true", dest="blobs", default=False,
                  help="Use blobs for images (required for webcasting)")

parser.add_option("-f", "--fullscreen",
                  action="store_true", dest="fullscreen", default=False,
                  help="Fullscreen display")

(options, args) = parser.parse_args()

IMGFORMAT = '<div><img class="gterm-fullimg" src="%s"></img></div>' if options.fullscreen else '<img class="gterm-blockimg" src="%s"></img><br>' 

if not args:
    args = os.listdir(Work_dir)
    args = [x for x in args if not x.startswith(".")]
    args.sort()

if gtermapi.Export_host:
    options.blobs = True

if options.blobs:
    print >> sys.stderr, "Loading images ..."

file_list = []
for filename in args:
    fullname = os.path.expanduser(filename)
    filepath = os.path.normcase(os.path.abspath(fullname))

    if not os.path.exists(filepath):
        print >> sys.stderr, "File %s not found" % filepath
        continue

    if not os.path.isfile(filepath):
        continue
    
    mimetype, encoding = mimetypes.guess_type(filepath)
    if mimetype and mimetype.startswith("image/"):
        if options.blobs:
            file_url = gtermapi.create_blob(from_file=filepath, content_type=mimetype)
        else:
            file_url = gtermapi.get_file_url(filepath, relative=True)
        file_list.append((file_url, filepath, filename))

if file_list:
    gtermapi.preload_images([x[0] for x in file_list])

if not file_list:
    sys.exit(1)
    
def display_file(file_url, filepath):
    gtermapi.write_html(IMGFORMAT % file_url, display=("fullscreen" if options.fullscreen else "block"), dir=Work_dir)

if not options.fullscreen:
    for file_url, filepath, filename in file_list:
        print filename
        display_file(file_url, filepath)
    sys.exit(0)

Stdin_fd = sys.stdin.fileno()
Saved_settings = termios.tcgetattr(Stdin_fd)

j = -1
try:
    print >> sys.stderr, "Slideshow: SPC/'f' => forward, BSP/'b' => back, 'q' or ESCAPE => quit\n'p' => pause, 'r' => resume"

    # Raw tty input without echo
    tty.setraw(Stdin_fd)
    while True:
        ch = sys.stdin.read(1)
        if ch == "\x03" or ch == "\x04" or ch == "\x1b" or ch == "q": # ^C/^D/ESC/q
            gtermapi.write_blank()
            sys.exit(0)

        if ch == "f" or ch == " ":
            jnew = j + 1
        elif ch == "b" or ch == "\x08" or ch == "\x7f": # Backspace
            jnew = j - 1
        elif ch == "r":
            jnew = j
        elif ch == "p":
            gtermapi.write_blank()
            continue
        else:
            continue

        jnew = max(0, min(jnew, len(file_list)-1) )
        if j == jnew and ch != "r":
            continue

        j = jnew
        display_file(*file_list[j][0:2])

except KeyboardInterrupt:
    sys.exit(1)
finally:
    termios.tcsetattr(Stdin_fd, termios.TCSADRAIN, Saved_settings)

