#!/usr/bin/env python
#

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

from __future__ import absolute_import, print_function

import mimetypes
import os
import sys
import tty
import termios

from optparse import OptionParser

try:
    import gterm
except ImportError:
    import graphterm.bin.gterm as gterm

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("", "--max_bytes", dest="max_bytes", default=10000000,
                  help="Max image file size in bytes (default: 10000000)", type="int")
parser.add_option("-f", "--fullscreen",
                  action="store_true", dest="fullscreen", default=False,
                  help="Fullscreen display (slideshow mode)")

(options, args) = parser.parse_args()

IMGFORMAT = '<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 gterm.Export_host or not gterm.Cookie:
    options.blobs = True

if options.blobs:
    print("Loading images ...", file=sys.stderr)

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("File %s not found" % filepath, file=sys.stderr)
        continue

    if not os.path.isfile(filepath):
        continue
    
    mimetype, encoding = mimetypes.guess_type(filepath)
    if mimetype and mimetype.startswith("image/"):
        file_url = ""
        if not gterm.Cookie:
            try:
                with open(filepath) as f:
                    content = f.read()
                    if len(content) > options.max_bytes:
                        print("Image larger %s than %d bytes; specify --max_bytes=..." % (filepath, options.max_bytes), file=sys.stderr)
                    else:
                        file_url = gterm.create_blob(content, content_type=mimetype, host="*")
            except Exception as excp:
                print("Error in reading file", filepath, excp, file=sys.stderr)
        elif options.blobs:
            file_url = gterm.create_blob(from_file=filepath, content_type=mimetype)
        else:
            file_url = gterm.get_file_url(filepath, relative=True)
        if file_url:
            file_list.append((file_url, filepath, filename))

if file_list and gterm.Cookie:
    gterm.preload_images([x[0] for x in file_list])

if not file_list:
    sys.exit(1)

display_opt = "fullscreen" if options.fullscreen else "block"

Overwrite=False
def display_file(file_url, filepath):
    global Overwrite
    if options.blobs:
        gterm.display_blob(gterm.get_blob_id(file_url), display=display_opt, overwrite=Overwrite)
    else:
        gterm.write_pagelet(IMGFORMAT % file_url, display=display_opt, dir=Work_dir, overwrite=Overwrite)
    Overwrite = True

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("Slideshow: SPC/'f' => forward, BSP/'b' => back, 'q' or ESCAPE => quit\n'p' => pause, 'r' => resume", file=sys.stderr)

    # 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
            gterm.write_blank(display="fullpage", exit_page=True)
            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":
            gterm.write_blank(display="fullpage")
            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)

