from app import db
from app.models import Ruleset


def add_rg(rsid, rg):
    rs = db.session.query(Ruleset).filter(Ruleset.uid == rsid).one()
    rs.add_rulegroup(rg)
    db.session.add(rs)
    db.session.commit()
    return True


def return_rg(rsid, rgid=None):
    rs = db.session.query(Ruleset).filter(Ruleset.uid == rsid).one()
    rules = rs.return_rulegroups()
    if rgid:
        rules = list(filter(lambda x: x.uid == rgid, rules))
    return rules


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
