#!/usr/bin/python
# -*- coding: utf-8 -*-

from nijmetrics import Application
import cPickle as pickle
import sys
import PIL
import PIL.Image, PIL.ImageDraw, PIL.ImageFilter
import itertools
import zlib
import nijmetrics

class QMapToImage(Application):

	def __init__(self, filename, dumpdir=None, cache=None):
		Application.__init__(self, dumpdir, cache)
		self.filename = filename
		
	def run(self):
	
		print "Loading '%s' ..." % (self.filename),
		f = file(self.filename, 'r')
		data = pickle.load(f)
		f.close()
		print "Done!"
		
		standardTable = {
			1: {'id': 1, 'color': '#2ca02c', 'label': 'High'},
			2: {'id': 2, 'color': '#ff7f0e', 'label': 'Medium'},
			3: {'id': 3, 'color': '#d62728', 'label': 'Low'},
		}
		
		for exid in data:
			print "Exercise ID",exid
			image = data[exid]['mark']
			print "  Image: %dx%d@%d" % (image['width'],image['height'],image['resolution'])
			#print data[exid]['assignment']
			overlaid = PIL.Image.new('RGBA', (image['width'],image['height']), (0,0,0,255))
			
			# Export the consensus maps
			for quality in data[exid]['consensus']['qmaps']:
				print "    Quality",quality
				map = data[exid]['consensus']['qmaps'][quality]
				
				if data[exid]['compressed']:
					map = eval(zlib.decompress(map))
					
				assert len(map) == image['width']*image['height']
				
				surface = PIL.Image.new('RGBA', (image['width'],image['height']), (0,0,0,0))

				maxval = float(data[exid]['consensus']['numcontributors'])#float(max(map))
				dc = PIL.ImageDraw.Draw(surface)
				
				assert quality in standardTable
				hcolor = standardTable[quality]['color']
				r,g,b = [int('0x'+a+b,16) for a,b in [x for x in itertools.izip(*[iter(hcolor[1:])]*2)]]
				
				# iterator over fixed-size chunks in a given list, see
				# http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python
				y = 0
				for line in itertools.izip_longest(*[iter(map)]*image['width']):
					for x in range(image['width']):
						value = line[x]
						alpha = int(min(255,round(255.0*float(value)/maxval)))
						dc.point((x,y), fill=(r,g,b,alpha))
					y += 1
				
				overlaid.paste(surface, mask=surface)
				surface.save(nijmetrics.sanitizefn(data[exid]['exercise']['name'])+'_Quality_'+str(quality)+'.png')
				
			overlaid.save(nijmetrics.sanitizefn(data[exid]['exercise']['name'])+'.png')
		

			# Export the consensus masks
			for threshold,imask in data[exid]['consensus']['masks'].iteritems():
				
				print "    Mask",threshold
				if data[exid]['compressed']:
					mask = eval(zlib.decompress(imask))
				else:
					mask = imask
			
				surface = PIL.Image.new('RGBA', (image['width'],image['height']), (0,0,0,255))

				dc = PIL.ImageDraw.Draw(surface)
				
				y = 0
				for line in itertools.izip_longest(*[iter(mask)]*image['width']):
					for x in range(image['width']):
						value = line[x]
						if value:
							dc.point((x,y), fill=(255,255,255,255))
					y += 1
				
				surface.save(nijmetrics.sanitizefn(data[exid]['exercise']['name'])+'_Mask_'+str(int(threshold*100.0))+'.png')
				
		return True