import os
import datetime

import psycopg2
import numpy as np
import pandas as pd

#import statsmodels.api as sm 

from statsmodels.genmod.generalized_linear_model import GLM
from statsmodels.genmod.families import Binomial
from statsmodels.genmod.families.links import probit

DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
cur = conn.cursor() # cursor needed to perform db ops

cur.execute("SELECT * FROM Iris;")
iris_df = pd.DataFrame(cur.fetchall())

X = np.array(iris_df.iloc[:, 0:4])
y = np.array(iris_df.iloc[:, 4] == 'virginica', dtype=int)

weight = np.ones(150) 

probit_link = probit()
bin_family = Binomial(probit_link)
my_glm = GLM(y, X, freq_weights = weight, family = bin_family)
my_glm_fit = my_glm.fit()

theta = my_glm_fit.params
current_dt = datetime.datetime.now()

cur.execute("INSERT INTO scores VALUES (%s, %s, %s, %s, %s)",
            (str(current_dt), theta[0], theta[1], theta[2], theta[3]))

conn.commit()

cur.close()
conn.close()  
