import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

# Import data
df = pd.read_csv('medical_examination.csv')

# Add 'overweight' column
#df['BMI'] = df['weight'] / (df['height']/100 * df['height']/100)
df['overweight'] = (df['weight'] / (df['height']/100 * df['height']/100)).apply(lambda x : 1 if x>25 else 0)

# Normalize data by making 0 always good and 1 always bad. If the value of 'cholestorol' or 'gluc' is 1, make the value 0. If the value is more than 1, make the value 1.
df['gluc'] = df['gluc'].replace({1:0, 2:1, 3:1})
df['cholesterol'] = df['cholesterol'].replace({1:0, 2:1, 3:1})

# Draw Categorical Plot
def draw_cat_plot():
    # Create DataFrame for cat plot using `pd.melt` using just the values from 'cholesterol', 'gluc', 'smoke', 'alco', 'active', and 'overweight'.
    df_cat = df[['active', 'alco', 'cholesterol', 'gluc', 'overweight', 'smoke','cardio']]


    # Group and reformat the data to split it by 'cardio'. Show the counts of each feature. You will have to rename one of the collumns for the catplot to work correctly.
    df_cat = df_cat.melt(id_vars='cardio')

    # Draw the catplot with 'sns.catplot()'
    fig = sns.catplot(x="variable", hue="value",data = df_cat,kind='count',col='cardio',sharey=True)
    fig.set_ylabels("total")
    fig.set_xlabels("variable")
    fig = fig.fig


    # Do not modify the next two lines
    fig.savefig('catplot.png')
    return fig


# Draw Heat Map
def draw_heat_map():
    # Clean the data
    df_heat = df[(df['ap_lo'] <= df['ap_hi'])
                 & (df['height'] >= df['height'].quantile(0.025))
                 & (df['height'] <= df['height'].quantile(0.975))
                 & (df['weight'] >= df['weight'].quantile(0.025))
                 & (df['weight'] <= df['weight'].quantile(0.975))]
    # Calculate the correlation matrix
    corr = df_heat.corr()

    # Generate a mask for the upper triangle
    mask =  np.triu(corr)



    # Set up the matplotlib figure
    fig, ax = plt.subplots(figsize=(11, 9))

    # Draw the heatmap with 'sns.heatmap()'
    ax = sns.heatmap(corr,linewidths=.5,annot=True,fmt='.1f',mask=mask,
        square=True,center=0,vmin=-0.1,vmax=0.25,cbar_kws={'shrink': .45,'format': '%.1f'})



    # Do not modify the next two lines
    fig.savefig('heatmap.png')
    return fig
