from app.main import main
from app.main.utils.common import response_message
from flask import request
from rulemall import RulesGroup
from app.main.utils.db_util import add_rg, return_rg, rm_rg


@main.post('/rg/<uuid:rsid>')
def create_rg(rsid):
    req = request.get_json()
    try:
        configs = {'name': req['name'], 'rules': req['rules']}
        rg = RulesGroup().from_dict(configs)
        add_rg(rsid, configs)
    except Exception as e:
        return response_message(str(e), 500)
    return response_message()


@main.get('/rg/<uuid:rsid>')
def read_all_rg(rsid):
    try:
        # TODO what do we what to send back?
        rgs = return_rg(rsid)
    except Exception as e:
        return response_message(str(e), 500)
    return response_message(rgs)


@main.get('/rg/<uuid:rsid>/<uuid:rgid>')
def read_rg(rsid, rgid):
    try:
        rgs = return_rg(rsid, rgid)
    except Exception as e:
        return response_message(str(e), 500)
    return response_message(rgs)


@main.put('/rg')
def update_rg():
    req = request.get_json()
    data = req['data']
    return response_message()


@main.delete('/rg/<uuid:rsid>')
def delete_rg(rsid):
    try:
        rgs = rm_rg(rsid)
    except Exception as e:
        return response_message(str(e), 500)
    return response_message(rgs)


@main.delete('/rg/<uuid:rsid>/<uuid:rgid>')
def delete_rg(rsid, rgid):
    try:
        rgs = rm_rg(rsid, rgid)
    except Exception as e:
        return response_message(str(e), 500)
    return response_message(rgs)
