# -*- coding: utf-8 -*-
"""
Created on Thu Oct 13 15:27:03 2016

This example downloads obesity data from Stats Canada (Federal
Government Open Data) and plots various charts on the data.

@author: Randy J. Fortier
"""

import urllib
import os
import shutil
import zipfile
import csv
import matplotlib.pyplot as plt

def toFloat(value):
    try:
        return float(value)
    except ValueError:
        return 0.0

# download the data file zip
url = 'http://www20.statcan.gc.ca/tables-tableaux/cansim/csv/01170002-eng.zip'
local_filename, headers = urllib.request.urlretrieve(url)
print('cwd:', os.getcwd())
shutil.move(local_filename, os.getcwd() + '/obesity.zip')

# extract the data file
zf = zipfile.ZipFile(os.getcwd() + '/obesity.zip', 'r')
csv_filename = zf.namelist()[0]
zf.extractall(path=os.getcwd())

years = [2009, 2011, 2013, 2015]

malesObese = []
femalesObese = []
males12to17in2015 = []

with open(csv_filename, newline='') as csvfile:
    datareader = csv.reader(csvfile, delimiter=',', quotechar='"')
    for row in datareader:
        year = row[0]
        gender = row[3]
        ageRange = row[4]
        weightCategory = row[5]
        estimate = row[6]
        count = toFloat(row[9])
        if ageRange == 'Ages 3 to 17' and estimate == 'Estimate':
            if gender == 'Females':
                if weightCategory == 'Obese':
                    femalesObese.append(count)
            elif gender == 'Males':
                if weightCategory == 'Obese':
                    malesObese.append(count)
        elif ageRange == 'Ages 12 to 17' and estimate == 'Estimate' and gender == 'Males' and year == '2015':
            males12to17in2015.append(count)

"""
fig = plt.figure()

malePlot = plt.plot(years, malesObese)
femalePlot = plt.plot(years, femalesObese)
plt.legend([malePlot, femalePlot], ['Males', 'Females'])
plt.ylim([0,20])
plt.xlim([2009,2015])
plt.grid(True)
plt.title('Obesity Trend')
plt.xlabel('year')
plt.ylabel('obesity rate')

fig.canvas.draw()
"""

explode = (0.0, 0.0, 0.0, 0.1)
labels = ['Underweight', 'Normal Weight', 'Overweight', 'Obese']
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']

plt.pie(males12to17in2015, explode=explode, labels=labels, colors=colors,
       autopct='%1.1f%%', shadow=True, startangle=90)
plt.title('Obesity in 12-17 year old males')
