import agate

"""
Explanation: Import agate for some agate time
End of explanation
"""


lunches2013 = agate.Table.from_csv('frl13.csv')
cleanLunches2013 = lunches2013.where(lambda row: row['FREEREDUCED13'] is not None)
print(cleanLunches2013)
print(len(cleanLunches2013.rows))

"""
Explanation: Pull in the 2013 lunch information csv, clean out any empty values, print table columns and lengths
End of explanation
"""


lunches2014 = agate.Table.from_csv('frl14.csv')
cleanLunches2014 = lunches2014.where(lambda row: row['FREEREDUCED14'] is not None)
print(cleanLunches2014)
print(len(cleanLunches2014.rows))

"""
Explanation: Pull in the 2014 lunch information csv, clean out any empty values, print table columns and lengths
End of explanation
"""


lunches2015 = agate.Table.from_csv('frl15.csv')
cleanLunches2015 = lunches2015.where(lambda row: row['FREEREDUCED15'] is not None)
print(cleanLunches2015)
print(len(cleanLunches2015.rows))

"""
Explanation: Pull in the 2015 lunch information csv, clean out any empty values, print table columns and lengths
End of explanation
"""


lunches1314 = cleanLunches2013.join(cleanLunches2014, 'CODISTSCH13', 'CODISTSCH14', inner=True )

"""
Explanation: Join the cleanLunches2013 & 2014 on district codes
End of explanation
"""


print(lunches1314)
print(len(lunches1314.rows))

"""
Explanation: View the new joined table
End of explanation
"""


lunches = lunches1314.join(cleanLunches2015, 'CODISTSCH13', 'CODISTSCH15', inner=True )

"""
Explanation: Final join between joined lunches1314 and lunches2015
End of explanation
"""


print(lunches)
print(len(lunches.rows))

"""
Explanation: View the final joined table
End of explanation
"""


change = lunches.compute([
    ('freelunch_change', agate.PercentChange('FREEREDUCED13', 'FREEREDUCED15')),
    ('enrollment_change', agate.PercentChange('ENROLLED13', 'ENROLLED15'))        
])

"""
Explanation: Compute the percent changes for both the free lunch enrollment and enrollment change for comparsion
End of explanation
"""


from decimal import Decimal
def round_freelunch_change(row):
    return row['freelunch_change'].quantize(Decimal('0.1'))
def round_enrollment_change(row):
    return row['enrollment_change'].quantize(Decimal('0.1'))
    
rounded_change = change.compute([
    ('pc_freelunch', agate.Formula(agate.Number(), round_freelunch_change)),
    ('pc_enrollment', agate.Formula(agate.Number(), round_enrollment_change)),
])

"""
Explanation: Make those percent changes to one decimal
End of explanation
"""


sorted_change = rounded_change.order_by('pc_freelunch', reverse=True)

"""
Explanation: Find those top free, reduced lunch percent change
End of explanation
"""


for_printing = sorted_change.select(['SCHOOLNAME13', 'pc_freelunch', 'pc_enrollment'])

"""
Explanation: Only need certain columns to print out
End of explanation
"""


for_printing.print_table()

"""
Explanation: Print out the final table
End of explanation
"""


