from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from models import get_connection_string
from marshmallow import Schema, fields

Base = declarative_base()

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    username = Column(String)
    pub_key = Column(String)

def add_new_user(user):
    connection_string = get_connection_string()
    engine = create_engine(connection_string)
    session = scoped_session(
        sessionmaker(autocommit=False, autoflush=False, bind=engine)
    )
    Base.metadata.create_all(engine)
    session.add(user)
    session.commit()

def get_all_users():
    connection_string = get_connection_string()
    engine = create_engine(connection_string)
    session = scoped_session(
        sessionmaker(autocommit=False, autoflush=False, bind=engine)
    )
    Base.metadata.create_all(engine)
    return session.query(User).all()

class UserSchema(Schema):
    username = fields.Str()
    pub_key = fields.Str()
