#!/usr/bin/env python
#

"""
giframe: Display file (or HTML from stdin) in inline iframe
"""

import mimetypes
import os
import sys
import time

from optparse import OptionParser

import gtermapi

usage = "usage: %prog [file|URL]"
parser = OptionParser(usage=usage)

parser.add_option("", "--opacity", dest="opacity", default=1.0,
                  help="Feed opacity (default: 1.0)")

(options, args) = parser.parse_args()
if args:
    if args[0].startswith("http:") or args[0].startswith("https:"):
        iframe_url = args[0]
    else:
        if gtermapi.Export_host:
            iframe_url = gtermapi.create_blob(from_file=args[0])
        else:
            iframe_url = gtermapi.get_file_url(args[0], relative=True, exists=True)

        if not iframe_url:
            print >> sys.stderr, "File %s not found" % args[0]
            sys.exit(1)
else:
    try:
        content = sys.stdin.read()
    except (EOFError, KeyboardInterrupt):
        content = None

    if not content:
        print >> sys.stderr, "Error in reading from stdin"
        sys.exit(1)

    iframe_url = gtermapi.create_blob(content, content_type="text/html")

IFRAMEFORMAT = '<iframe src="%s" width="100%%" height="95%%"></iframe><pre>Click here and type Control-C to exit</pre>'

gtermapi.write_html(IFRAMEFORMAT % iframe_url, display="fullscreen", add_headers={"opacity": options.opacity})

try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    gtermapi.write_blank()

