#!/bin/python2.7

import csv
import argparse
import palettable

ipe_color_tag = "<color name=\"{}\" value=\"{} {} {}\"/>"

def get_colorbrewer(palette):
	colorbrewer = dict()
	colorbrewer.update([(name, cls) for name, cls in palettable.colorbrewer.diverging.__dict__.items() if isinstance(cls, palettable.colorbrewer.colorbrewer.BrewerMap)])
	colorbrewer.update([(name, cls) for name, cls in palettable.colorbrewer.qualitative.__dict__.items() if isinstance(cls, palettable.colorbrewer.colorbrewer.BrewerMap)])
	colorbrewer.update([(name, cls) for name, cls in palettable.colorbrewer.sequential.__dict__.items() if isinstance(cls, palettable.colorbrewer.colorbrewer.BrewerMap)])
	
	if(palette in colorbrewer):
		return colorbrewer[palette].hex_colors 
	
	return None
	
def hex_to_rgb(value):
    value = value.lstrip('#')
    lv = len(value)
    return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))

def rgb_to_percent(rgb):
    return [float(val)/256 for val in rgb]

def color_to_precent(color):
	if color[0].startswith("#"):
		return rgb_to_percent(hex_to_rgb(color))

def get_tag(name, color):
	return ipe_color_tag.format(name, color[0], color[1], color[2])

def handle_file(m_file):
	return [line.strip('\n').strip('\t') for line in m_file]

def get_names(path):
	with open(args.names[0], 'rb') as namefile: 
		return handle_file(namefile)
	
def zip_names_colors(colors, names = []):
	if len(names) is 0:
		names = [color for color in colors]
			
	return zip(names, colors)



parser = argparse.ArgumentParser(usage = '%(prog)s [-h] (-z COLORS NAMES | -c CSV | -b PALETTE NAMES)')
group = parser.add_mutually_exclusive_group(required = True)
group.add_argument('-z', '--zip', 
					metavar='COLORS',
					help = 'Given a file of colors and names zip them together. Files should be simple one name/color per line.')
					
group.add_argument('-c', '--csv',
					metavar='CSV',
					help = 'Read the csv file, first column names, second colors. Expected delimiter is ;')
					
group.add_argument('-b', '--brewer',  
					metavar='PALETTE',
					help = 'Zip a name file with the colors provided in the brewer palette. The name file should be one name per line.')
parser.add_argument('names', nargs=argparse.REMAINDER, help = 'Provide a file with names to zip and brewer. If no file is provided the hex values will be taken as names.', metavar = 'NAMES')
					
args = parser.parse_args()
print args

names = []
if len(args.names) is not 0:
	names = get_names(args.names[0])
	
print names

colormap = []
if args.zip is not None:
	with open(args.zip, 'rb') as colorfile:
		colors = handle_file(colorfile)
		colormap = zip_names_colors(colors, names)
				
elif args.brewer is not None:
	palette_name = args.brewer
	palette = get_colorbrewer(palette_name)	
	
	if palette is None:
		print "Palette " + palette_name + " does not exist."
	else:
		colormap = zip_names_colors(palette, names)
		
elif args.csv is not None:
	with open(args.csv, 'rb') as colorfile:
		reader = csv.reader(colorfile, delimiter = ';')
		for row in reader:	
			colormap = [row for row in reader]
						
for c in colormap:
	print get_tag(c[0],color_to_precent(c[1]))
	
