from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Sequence, ForeignKey, DateTime
from sqlalchemy.orm import sessionmaker, relationship, backref

from datetime import time, datetime
import json

engine = create_engine('postgresql://postgres:joseph@localhost/mmf')
Base = declarative_base()
Session = sessionmaker(bind=engine)

class User(Base):
	__tablename__ = "user"

	id = Column(Integer, Sequence("user_id_seq"), primary_key=True)
	name = Column(String)
	password = Column(String)


class DailyNutrition(Base):
	__tablename__ = "dailynutrition"
	
	id = Column(Integer, Sequence("dailynutrition_id_seq"), primary_key=True)
	
	workout_count = Column(String)
	bmr = Column(String)
	weight = Column(String)
	total_calories = Column(String)
	daily_calories_budget_date = Column(String)
	age = Column(String)
	height = Column(String)
	workout_calories_burned = Column(String)
	total_fiber = Column(String)
	total_protein = Column(String)
	gender = Column(String)
	activity_frequency = Column(String)
	total_foods = Column(String)
	total_fat = Column(String)
	timestamp = Column(DateTime)
	tod = Column(String)

	
	def set_time(self):
		tod = datetime.time(datetime.now())
		if tod < time(11,00):
			tod = "morning"
		elif  time(11,00) < tod <= time(15,00):
			tod = "afternoon"
		else:
			tod = "evening"
		self.tod = tod
		self.timestamp = datetime.now()

	def set_fields(self, jsonObj):
		output = jsonObj['output']
		self.workout_count = output['workout_count']
		self.bmr = output['bmr']['value']
		self.weight =  output['weight']['value']
		self.total_calories = output['total_calories']
		self.daily_calories_budget_date = output['daily_calorie_budget_date']
		self.age = output['age']
		self.height = output['height']
		self.workout_calories_burned = output['workout_calories_burned']
		self.total_fiber = output['total_fiber']
		self.total_protein = output['total_protein']
		self.gender = output['gender']
		self.activity_frequency = output['activity_frequency']
		self.total_foods = output['total_foods']
		self.total_fat = output['total_fat']
		
	user_id = Column(Integer, ForeignKey('user.id'))
	user = relationship('User', backref=backref('dailynutrition', order_by=id))

Base.metadata.create_all(engine)
