from app.main import main
from app.main.utils.common import response_message
from flask import request
from rulemall import RulesGroup, Rule
from app.main.utils.db_util import add_obj, return_obj, rm_obj, return_project_rules


@main.post('/api/<what>')
def create_obj(what):
    """
    create rulegroup, rule or datastructure
    """
    req = request.get_json()
    if what == 'rg':
        try:
            RulesGroup().from_dict(req.copy())
        except Exception:
            return response_message(str('Not a Valid rulegroup'), 500)
    elif what == 'rule':
        try:
            if req['rule'].get('validator_parameters'):
                empty_cols = [x[0] for x in list(filter(lambda x: x[1] == '', req['rule']['validator_parameters'].items()))]
                for col in empty_cols:
                    req['rule']['validator_parameters'].pop(col)
            Rule().from_dict(req['rule'].copy())
        except Exception:
            return response_message(str('Not a Valid rule'), 500)
    if what not in ['rule', 'ds', 'rg']:
        return response_message(f"{what} doesn't exist", 500)

    try:
        return response_message(add_obj(req, what))
    except Exception as e:
        return response_message(str(e), 500)


@main.get('/api/<what>/<uuid:oid>')
def read_obj(what, oid):
    try:
        rg = return_obj(oid, what)
    except Exception as e:
        return response_message(str(e), 500)
    return response_message(rg)


@main.delete('/api/<what>/<uuid:oid>')
def delete_obj(what, oid):
    try:
        rg = rm_obj(oid, what)
    except Exception as e:
        return response_message(str(e), 500)
    return response_message(rg)


@main.get('/api/rule/all/<project_id>')
def read_all_rules(project_id):
    try:
        rg = return_project_rules(project_id)
    except Exception as e:
        return response_message(str(e), 500)
    return response_message(rg)
