# Tuberculosis.py
# Interactive sketch showing how the rate of TB per population has changed over time
# for several West African countries
from Processing import *

# Load all data from the file and convert to proper types
def loadData():
    data = []

    # Open file
    f = open( "reduced.csv", "r" )
    
    # Loop over all lines in file.
    for line in f:
    
        # Split items
        items = line.split(',')

        # Convert to usable data types
        country = items[0]
        year = int( items[1] )
        pop = int( items[2] ) / 100000
        tb = float( items[3] )

        # Store data together in a dictionary
        item = {'country':country, 'year':year, 'population':pop, 'tb':tb}

        # Add to master list
        data.append( item )

    # Close file
    f.close()

    return data

# Draw all data for a particular country at the given y value
def drawCountry(filter, y):
    mx, my = mouseX(), mouseY()

    # Loop over all data
    for d in data:
        # If not country of interest, continue to next data item
        if d['country'] != filter:
            continue

        # Calculate x position based on year, and diameter based on tb per population
        x = 45*(d['year'] - 1989)
        diam = 5.0*(d['tb']/d['population'])

        # If mouse is within circle, also change fill and draw data
        if dist(mx, my, x, y) < 0.5*diam:
            fill(0)
            msg = "%(country)s, %(year)s, tb: %(tb)s, pop: %(population)s" % d
            text(msg, 10, 490)
            fill(255, 128, 128)
        else:
            fill(255)

        ellipse(x, y, diam, diam)

# Draw all countries
def draw(o, e):
    background(128)
    drawCountry('Mali', 50)
    drawCountry('Senegal', 150)
    drawCountry('Guinea', 250)
    drawCountry('Sierra Leone', 350)
    drawCountry('Liberia', 450)

# Create Sketch Window
window(950, 500)
noStroke()

# Load all data from the file
data = loadData()

# Draw once to start
draw(None, None)

# Update drawing whenever mouse moves
onMouseMoved += draw
