from app.extensions import db


class AppSettings(db.Model):
    __tablename__ = 'app_settings'

    key = db.Column(db.String(100), primary_key=True)
    value = db.Column(db.Text, nullable=False)

    @staticmethod
    def get(key, default=''):
        setting = db.session.get(AppSettings, key)
        return setting.value if setting else default

    @staticmethod
    def set(key, value):
        setting = db.session.get(AppSettings, key)
        if setting:
            setting.value = str(value)
        else:
            setting = AppSettings(key=key, value=str(value))
            db.session.add(setting)
        db.session.commit()

    @staticmethod
    def get_bool(key, default=False):
        val = AppSettings.get(key, '')
        if val == '':
            return default
        return val.lower() in ('true', '1', 'yes')
