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

from nijmetrics import Application
import cPickle as pickle
import sys
import itertools
import zlib

class QMapToCSV(Application):

	def __init__(self, filename, dumpdir=None, cache=None):
		Application.__init__(self, dumpdir, cache)
		self.filename = filename
		
	def run(self):
	
		f = file(self.filename, 'r')
		data = pickle.load(f)
		f.close()
		
		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 %s (ID=%d)" % (data[exid]['exercise']['name'],exid)
			
			image = data[exid]['mark']
			#print "  Image: " % ()
			
			print "  Consensus"
			for quality in data[exid]['consensus']['qmaps']:
				map = data[exid]['consensus']['qmaps'][quality]
			
				if data[exid]['compressed']:
					map = eval(zlib.decompress(map))
			
				assert len(map) == image['width']*image['height']					
			
				filename = 'Exercise_%d_Image_%dx%d@%d_Consensus_Quality_%d.csv' % (exid, image['width'],image['height'],image['resolution'], quality)

				f = file(filename,'w')
				for line in itertools.izip_longest(*[iter(map)]*image['width']):
					f.write(';'.join((str(x) for x in iter(line)))+'\n')
				f.close()

			count = 0
			for userid in data[exid]['users']:
				print "  User %d  (%.2f%%)" % (userid,float(count)/float(len(data[exid]['users']))*100.0)
				count += 1
				
				for quality in data[exid]['users'][userid]['qmaps']:
					print "    Quality",quality
		
					map = data[exid]['users'][userid]['qmaps'][quality]
					
					if data[exid]['compressed']:
						map = eval(zlib.decompress(map))
					
					assert len(map) == image['width']*image['height']					
					
					filename = 'Exercise_%d_Image_%dx%d@%d_User_%d_Quality_%d.csv' % (exid, image['width'],image['height'],image['resolution'], userid, quality)

					f = file(filename,'w')
					for line in itertools.izip_longest(*[iter(map)]*image['width']):
						f.write(';'.join((str(x) for x in iter(line)))+'\n')
					f.close()
					
		return True