"""Tool for visualising sign detection results on images"""

from urlparse import urlparse
from PIL import Image, ImageDraw
import argparse
import json
import os.path
import urllib, cStringIO

parser = argparse.ArgumentParser()
parser.add_argument('--input', required=True, help='JSON file with with detection results')
parser.add_argument('--output_dir', required=True, help='directory for resulting images')
args = parser.parse_args()

def url_to_filename(url):
    name = urlparse(url).path
    return name.strip('/').replace('/', '_') + '.jpg'


with open(args.input) as input:
    json_data = json.load(input)

for item in json_data['detection_task_results']:
    source = item['source']
    filename = os.path.join(args.output_dir, url_to_filename(source))
    print 'Processing', filename
    file = cStringIO.StringIO(urllib.urlopen(source).read())
    try:
       img = Image.open(file)
    except:
       print 'Cannot open image', source
       continue
    draw = ImageDraw.Draw(img)

    for solution in item['solutions']:
        box = solution['bbox']
        xmin, ymin = tuple(box[0])
        xmax, ymax = tuple(box[1])
        # not using draw.rectangle() since it does not have line width attribute
        draw.line(
            ((xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin), (xmin, ymin)),
            fill = (0,255,0),
            width = 2)

    img.save(filename)

