import csv
from BeautifulSoup import BeautifulSoup

### Purp/Red
colors = ["#F1EEF6", "#D4B9DA", "#C994C7", "#DF65B0", "#DD1C77", "#980043"]

# Base SVG file
basemap_file = open('counties_basemap.svg', 'r')
svg = basemap_file.read()
soup = BeautifulSoup(svg)
paths = soup.findAll('path')
path_style = 'font-size:12px;fill-rule:nonzero;stroke:#000000;stroke-opacity:1;stroke-width:0.1;stroke-miterlimit:4;stroke-dasharray:none;stroke-linecap:butt;marker-start:none;stroke-linejoin:bevel;fill:'

# Unemployment rates
reader = csv.reader(open('data/unemployment-formatted.txt'), delimiter=",")

# Store unemployment in dictionary
unemployment = {}
for row in reader:
    laus = row[0]
    fips_id = row[1] + row[2]
    month = row[4]
    rate = float(row[5])
    
    if month not in unemployment:
        unemployment[month] = { fips_id: rate }
    else:
        unemployment[month][fips_id] = rate


# Create and save maps
for month, rates in unemployment.items():
    filename = 'maps/' + month + '.svg'
    the_map = open(filename, 'w')
    
    for p in paths:
        if p['id'] not in ["State_Lines", "separator"]:
            try:
                rate = rates[p['id']]
            except:
                continue
        
            if rate > 10:
                color_class = 5
            elif rate > 8:
                color_class = 4
            elif rate > 6:
                color_class = 3
            elif rate > 4:
                color_class = 2
            elif rate > 2:
                color_class = 1
            else:
                color_class = 0
    
            color = colors[color_class]
            p['style'] = path_style + color
    
    the_map.write(soup.prettify())
    the_map.close()