"""Tool for visualising sign detection results from each user on images"""

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

parser = argparse.ArgumentParser()
parser.add_argument('--output_dir', required=True, help='directory for resulting images')
parser.add_argument('--host', required=True, help='Toloka host')
parser.add_argument('--auth_header', required=True, help='Toloka auth header')
parser.add_argument('--pool_id', required=True, help='Toloka pool id')
args = parser.parse_args()

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

if not args.host.startswith('https://'):
    url = 'https://' + args.host
else:
    url = args.host
url = url + '/api/v1/assignments'

headers = {'Authorization': args.auth_header}

hasMore = True
lastId = ''

userResults = {}

while hasMore:
    params = {'pool_id': args.pool_id, 'sort': 'id', 'limit': 100}
    if lastId:
        params['id_gt'] = lastId
    resp = requests.get(url=url, headers=headers, params=params, verify=False)
    data = json.loads(resp.content)

    for item in data['items']:
        uid = item['user_id']
        if uid not in userResults:
            userResults[uid] = []
        userResults[uid].append(item)

    hasMore = data['has_more']
    lastId = data['items'][-1]['id']


for key, values in userResults.items():
    print 'User', key, ' --> ResultsCnt:', len(values)
    userDir = os.path.join(args.output_dir, key)
    if not os.path.exists(userDir):
        os.makedirs(userDir)
    print 'userDir:', userDir
    for item in values:
        if item['status'] not in ['ACCEPTED', 'REJECTED', 'SUBMITTED']:
            continue;
        resultDir = os.path.join(userDir, item['id'])
        print 'resultDir:', resultDir
        print 'status:', item['status']
        if not os.path.exists(resultDir):
            os.makedirs(resultDir)
        tasks = item['tasks']
        solutions = item['solutions']
        size = len(tasks)
        for i in range(0,size):
            source = tasks[i]['input_values']['source']
            polygons = solutions[i]['output_values']['polygons']

            filename = os.path.join(resultDir, url_to_filename(source))
            file = cStringIO.StringIO(urllib.urlopen(source).read())
            try:
                img = Image.open(file)
            except:
                print 'Cannot open image', source
                continue
            draw = ImageDraw.Draw(img)

            jsonPolygons = json.loads(polygons)
            for box in jsonPolygons:
                xmin, ymin = tuple(box[0])
                xmax, ymax = tuple(box[1])
                draw.line(
                    ((xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin), (xmin, ymin)),
                    fill = (0,255,0),
                    width = 2)

            img.save(filename)

