from aiopg.sa import create_engine as async_engine
from sqlalchemy import ForeignKey, CheckConstraint
from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String, Text, DECIMAL, Boolean, exc, event, MetaData, select, DateTime
from sqlalchemy import desc
from sqlalchemy import func
from sqlalchemy.sql.expression import true, false
from sqlalchemy.engine.url import URL
from sqlalchemy.orm import sessionmaker, relationship, backref
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative import declarative_base, as_declarative, declared_attr
import json

DATABASE = {
    'drivername': 'postgres',
    'host': '127.0.0.1',
    'port': '5432',
    'username': 'xmasdamin',
    'password': 'xmasadmin',
    'database': 'xmasdb'
}

Base = declarative_base()
metadata = MetaData()
engine = create_engine(URL(**DATABASE))
Session = sessionmaker(bind=engine)

session = Session()

class Attendee(Base):
    __tablename__ = 'attendee'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    guest = Column(Boolean)
    cat = Column(String)

    def serialize(self):
        return {
            'id': self.id,
            'name': self.name,
            'cat': self.cat,
            'guest': str(self.guest)
        }


async def add_attendee(name, guest, cat):
    attendee = session.query(Attendee).filter(Attendee.name == name).first()
    if attendee is None:
        attendee = Attendee(name=name, guest=guest, cat=cat)
    else:
        attendee.name = name
        attendee.guest = guest
        attendee.cat = cat

    if attendee is not None:
        session.add(attendee)
        session.commit()
        return True

    else:
        return False

async def fetch_attendees():
    attendees = session.query(Attendee).all()
    if attendees is not None:
        return attendees
    else:
        return False