#!/usr/bin/env python
#

"""
gqrcode: Display QR code
"""
import os
import sys
import gterm

import cStringIO as StringIO

try:
    import qrcode
except ImportError:
    print >> sys.stderr, "Please install qrcode (and PIL) packages"
    sys.exit(1)

usage = "usage: %prog [-h ... ] text"

form_parser = gterm.FormParser(usage=usage, title="Display QR code: ", command="gqrcode")
form_parser.add_argument(label="", help="Text to QR encode")
form_parser.add_option("border", 4, short="b", help="Border size (default 4)")
form_parser.add_option("fullscreen", False, short="f", help="Fullscreen display", raw=True)
form_parser.add_option("output", False, short="o", help="Write to standard output")
form_parser.add_option("pixel", 15, short="p", help="Pixel count per box (default 15)")
form_parser.add_option("terminal", False, short="t", help="Display URL for this terminal")

(options, args) = form_parser.parse_args()

if not gterm.Lterm_cookie or not sys.stdout.isatty():
    options.output = True

if options.terminal and gterm.Lterm_cookie:
    text = gterm.env("URL", "")
else:
    if not args or not args[0]:
        gterm.write_form(form_parser.create_form(), command="gqrcode")
        sys.exit(1)
    text = args[0]

qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=options.pixel,
    border=options.border,
)
qr.add_data(text)
qr.make(fit=True)

img = qr.make_image()

img_io = StringIO.StringIO()
img.save(img_io, "png")
img_io.seek(0)
img_data = img_io.getvalue()

if options.output:
    sys.stdout.write(img_data)
else:
    data_uri = "data:image/gif;base64,"+img_data.encode("base64")
    IMGFORMAT = '<div><img class="gterm-fullimg" src="%s"></img><h1><code>%s</code></h1></div>' if options.fullscreen else '<center><img class="gterm-blockimg" src="%s"></img></center><center><h1><code>%s</code></h1></center>' 

    gterm.write_pagelet(IMGFORMAT % (data_uri, text), display=("fullscreen" if options.fullscreen else "block"))

    
