# Path: plugin.py
# class Plugin:
#     def __init__(self):
#         self.documents = Documents(self)
#         try: self.name
#         except: self.name = self.__class__.__name__.lower()
#         try: self.description
#         except: self.description = 'This plugin has no description.'
#         if self.__class__ is Plugin:
#             raise NotImplementedError
# 
#     @property
#     def user(self):
#         return app.current_user
# 
#     def process(self, request):
#         pass
# 
#     def unload(self):
#         pass
# 
# Path: database.py
# def get_session():
# def teardown_session(exception):
# 
# Path: database.py
# def get_session():
# def teardown_session(exception):
# 
# Path: models/user.py
# class User(TableBase, UserMixin):
#     """A user."""
# 
#     __tablename__ = 'user'
#     id = Column(Integer, primary_key=True)
#     email = Column(String(63), unique=True)
#     passwordhash = Column(String(127), nullable=False)
#     salt = Column(String(127), nullable=False)
#     username = Column(String(127))
#     if os.getenv('FLASK_TESTING'):
#         avatar = Column(String(16777215))
#     else:
#         avatar = Column(MEDIUMTEXT())
#     description = Column(Text())
#     education = Column(Text())
#     major = Column(Text())
# 
#     def __init__(self, email, password, username):
#         self.email = email
#         self.set_password(password)
#         self.username = username
# 
#     def set_password(self, password):
#         """hash and save the password"""
#         self.salt = random_string(10)
#         s = hashlib.sha256()
#         s.update(password.encode('utf-8'))
#         s.update(self.salt.encode('utf-8'))
#         self.passwordhash = s.hexdigest()
# 
#     def check_password(self, password):
#         """hash and check the password"""
#         s = hashlib.sha256()
#         s.update(password.encode('utf-8'))
#         s.update(self.salt.encode('utf-8'))
#         return self.passwordhash == s.hexdigest()
# 
#     @classmethod
#     def get_user_by_email(cls, email):
#         return session.query(cls).filter_by(email=email).first()
# 
#     @classmethod
#     def get_user_by_id(cls, id):
#         return session.query(cls).get(id)
# 
# Path: plugins/pano.py
# class PanoDocument(TableBase, PluginDocument):
# class Pano(Plugin):
#     def __init__(self, owner, title='Untitled', text=''):
#     def __init__(self):
#     def process(self, request):
#     def new(self, title, data, public, img, **kwargs):
#     def save(self, id, title, data, img, **kwargs):
#     def list(self, **kwargs):
#     def load(self, id, **kwargs):
#     def delete(self, id, **kwargs):
#     def get_event_data(self, **kwargs):
#     def submit_comment(self, comment, event_id, **kwargs):
#     def submit_praise(self, modify, event_id, **kwargs):
#     def get_project_data(self, **kwargs):
#     def match_node(self, s, **kwargs):


from plugin import Plugin
from database import TableBase, Column, Text
from database import engine, session
from flask_login import current_user, login_required, login_user, logout_user
from models import User
from plugins.pano import __plugin__ as pano


class user_model(Plugin):
    def __init__(self):
        super().__init__()
        print('user_model plugin loaded')
        self.name = 'user_model'

    def process(self, request):
        if request['action'] == 'validate_login':
            print('Login: ', request['email'], request['password'])
            email = request['email']
            password = request['password']
            user = User.get_user_by_email(email)
            if not user:
                return {'success': False, 'error': 'Email not found'}
            elif not user.check_password(password):
                return {'success': False, 'error': 'Email or password incorrect'}
            else:
                login_user(user, remember='remember' in request)
                return {'success': True}
        elif request['action'] == 'create_user':
            print('Create: ', request['email'], request['password'], request['username'])
            email = request['email']
            password = request['password']
            username = request['username']
            if User.get_user_by_email(email):
                return {'success': False, 'error': 'Email already exists'}
            user = User(email, password, username)
            session.add(user)

# Path: plugin.py
# class Plugin:
#     def __init__(self):
#         self.documents = Documents(self)
#         try: self.name
#         except: self.name = self.__class__.__name__.lower()
#         try: self.description
#         except: self.description = 'This plugin has no description.'
#         if self.__class__ is Plugin:
#             raise NotImplementedError
# 
#     @property
#     def user(self):
#         return app.current_user
# 
#     def process(self, request):
#         pass
# 
#     def unload(self):
#         pass
# 
# Path: database.py
# def get_session():
# def teardown_session(exception):
# 
# Path: database.py
# def get_session():
# def teardown_session(exception):
# 
# Path: models/user.py
# class User(TableBase, UserMixin):
#     """A user."""
# 
#     __tablename__ = 'user'
#     id = Column(Integer, primary_key=True)
#     email = Column(String(63), unique=True)
#     passwordhash = Column(String(127), nullable=False)
#     salt = Column(String(127), nullable=False)
#     username = Column(String(127))
#     if os.getenv('FLASK_TESTING'):
#         avatar = Column(String(16777215))
#     else:
#         avatar = Column(MEDIUMTEXT())
#     description = Column(Text())
#     education = Column(Text())
#     major = Column(Text())
# 
#     def __init__(self, email, password, username):
#         self.email = email
#         self.set_password(password)
#         self.username = username
# 
#     def set_password(self, password):
#         """hash and save the password"""
#         self.salt = random_string(10)
#         s = hashlib.sha256()
#         s.update(password.encode('utf-8'))
#         s.update(self.salt.encode('utf-8'))
#         self.passwordhash = s.hexdigest()
# 
#     def check_password(self, password):
#         """hash and check the password"""
#         s = hashlib.sha256()
#         s.update(password.encode('utf-8'))
#         s.update(self.salt.encode('utf-8'))
#         return self.passwordhash == s.hexdigest()
# 
#     @classmethod
#     def get_user_by_email(cls, email):
#         return session.query(cls).filter_by(email=email).first()
# 
#     @classmethod
#     def get_user_by_id(cls, id):
#         return session.query(cls).get(id)
# 
# Path: plugins/pano.py
# class PanoDocument(TableBase, PluginDocument):
# class Pano(Plugin):
#     def __init__(self, owner, title='Untitled', text=''):
#     def __init__(self):
#     def process(self, request):
#     def new(self, title, data, public, img, **kwargs):
#     def save(self, id, title, data, img, **kwargs):
#     def list(self, **kwargs):
#     def load(self, id, **kwargs):
#     def delete(self, id, **kwargs):
#     def get_event_data(self, **kwargs):
#     def submit_comment(self, comment, event_id, **kwargs):
#     def submit_praise(self, modify, event_id, **kwargs):
#     def get_project_data(self, **kwargs):
#     def match_node(self, s, **kwargs):


# Path: plugins/user_model.py
from plugin import Plugin
from database import TableBase, Column, Text
from database import engine, session
from flask_login import current_user, login_required, login_user, logout_user
from models import User
from plugins.pano import __plugin__ as pano



class user_model(Plugin):
    def __init__(self):
        super().__init__()
        print('user_model plugin loaded')
        self.name = 'user_model'

    def process(self, request):
        if request['action'] == 'validate_login':
            print('Login: ', request['email'], request['password'])
            email = request['email']
            password = request['password']
            user = User.get_user_by_email(email)
            if not user:
                return {'success': False, 'error': 'Email not found'}
            elif not user.check_password(password):
                return {'success': False, 'error': 'Email or password incorrect'}
            else:
                login_user(user, remember='remember' in request)
                return {'success': True}
        elif request['action'] == 'create_user':
            print('Create: ', request['email'], request['password'], request['username'])
            email = request['email']
            password = request['password']
            username = request['username']
            if User.get_user_by_email(email):
                return {'success': False, 'error': 'Email already exists'}
            user = User(email, password, username)
            session.add(user)

            session.commit()