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
from datetime import datetime


@main.post('/rg/<uuid:rsid>')
def create_rg(rsid):
    '''
    create rulegroup
    json should have rules and name values to create the rulegroup
    rulegroup's uid will be returned
    '''
    req = request.get_json()
    try:
        configs = {'name': req['name'], 'rules': req['rules'], 'created_date': str(datetime.now()),
                   'modified_date': str(datetime.now())}
        rg = RulesGroup().from_dict(configs)
        return response_message(add_rg(rsid, configs))
    except Exception as e:
        return response_message(str(e), 500)


@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)


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


@main.delete('/rg/<uuid:rsid>')
def delete_rg_all(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)
