from app import db
from app.models import Ruleset, RuleGroup


def add_rs(config):
    rs = Ruleset()
    rs.from_dict(config)
    db.session.add(rs)
    db.session.commit()
    return str(rs.uid)


def add_rg(rsid, rg):
    rs = db.session.query(Ruleset).filter(Ruleset.uid == rsid).one()
    l = len(rs.rulegroups)
    rs.add_rulegroup(rg)
    db.session.add(rs)
    db.session.commit()
    return str(rs.rulegroups[l].uid)


def return_rg(rsid, rgid=None):
    rs = db.session.query(Ruleset).filter(Ruleset.uid == rsid).one()
    rgs = rs.return_rulegroups()
    if rgid:
        try:
            rule = db.session.query(RuleGroup).filter(RuleGroup.uid == rgid, RuleGroup.rsid == rsid).one()
        except Exception:
            raise Exception('rulegroup not found')
        rgs = {'name': rule.name, 'rules': rule.rules}
    return rgs, rs


def rm_rg(rsid, rgid=None):
    rs = db.session.query(Ruleset).filter(Ruleset.uid == rsid).one()
    if rgid:
        rs = Ruleset()
        rs.rulegroups = list(filter(lambda x: x.uid != rgid, rs.rulegroups))
    else:
        db.session.delete(rs)
    db.session.commit()
    return rsid
