#!/usr/bin/env python
#

"""
gqrcode: Display QR code
"""

from __future__ import absolute_import, print_function

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

from io import BytesIO

try:
    import qrcode
except ImportError:
    print("Please install qrcode (and PIL) packages", file=sys.stderr)
    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.Cookie or not sys.stdout.isatty():
    options.output = True

if options.terminal and gterm.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 = BytesIO()
img.save(img_io, "png")
img_io.seek(0)
img_data = img_io.getvalue()

if options.output:
    os.write(sys.stdout.fileno(), 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"))

    
