from models.User import User, UserSchema, add_new_user

class Registrar(object):
    def __init__(self, username=None, pub_key=None, *args, **kwargs):
        self.username = username
        self.pub_key = pub_key

    def get_serializable(self):
        return self.__dict__

    def valid_input(self):
        return self.username is not None and self.pub_key is not None

    def persist(self):
        try:
            user = User(username=self.username,pub_key=self.pub_key)
            add_new_user(user)
            schema = UserSchema()
            return schema.dump(user)
        except Exception as exception:
            return FailedPersistenceHandler(
                "Error: failed to persist", self.username, self.pub_key
            ).get_serializable()

    def register(self):
        return (
            InvalidInputHandler(
                "Error: invalid input", self.username, self.pub_key
            ).get_serializable()
            if not self.valid_input()
            else self.persist()
        )


class InvalidInputHandler:
    def __init__(self, status, username=None, pub_key=None):
        self.status = status
        self.username = "Missing username" if username is None else username
        self.pub_key = "Missing pub_key" if pub_key is None else pub_key

    def get_serializable(self):
        return self.__dict__


# Stub for current lack of a database.
class FailedPersistenceHandler:
    def __init__(self, status, username=None, pub_key=None):
        self.status = status
        self.username = "username..." if username is None else username
        self.pub_key = "pub_key..." if pub_key is None else pub_key

    def get_serializable(self):
        return self.__dict__
