from app import db
from app.models import Dataset, RuleGroup, Rule


def add_obj(config, what):
    dct = {'ds': Dataset, 'rg': RuleGroup, 'rule': Rule}
    obj = dct[what]()
    obj.from_dict(config)
    db.session.add(obj)
    db.session.commit()
    return str(obj.uid)


def return_obj(oid, what, to_dict=True):
    dct = {'ds': Dataset, 'rg': RuleGroup, 'rule': Rule}
    obj = db.session.query(dct[what]).filter(dct[what].uid == oid).one()
    if to_dict:
        return obj.to_dict()
    else:
        return obj


def return_all_objs(what, to_dict=True):
    dct = {'ds': Dataset, 'rg': RuleGroup, 'rule': Rule}
    objs = db.session.query(dct[what]).all()
    if to_dict:
        return [obj.to_dict() for obj in objs]
    else:
        return objs


def rm_obj(oid, what):
    dct = {'ds': Dataset, 'rg': RuleGroup, 'rule': Rule}
    obj = db.session.query(dct[what]).filter(dct[what].uid == oid).one()
    db.session.delete(obj)
    db.session.commit()
    return True


def return_project_rules(project_id, flat=True):
    rules = db.session.query(Rule).filter(Rule.project_id == project_id).all()
    return [r.to_dict(flat=flat) for r in rules]
