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


@main.post('/api/<what>')
def create_obj(what):
    """
    create rulegroup, rule or datastructure
    """
    req = request.get_json()
    if what == 'rg':
        try:
            rg = RulesGroup()
            rg.from_dict(req.copy())
            del rg
        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)
            r = Rule()
            r.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:
        obj = return_obj(oid, what)
    except Exception as e:
        return response_message(str(e), 500)
    return response_message(obj)


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


@main.get('/api/rule/all/<project_id>')
def read_all_rules(project_id):
    flat = request.args.get('flat', True)
    if flat == 'false':
        flat = False
    try:
        rule = return_project_rules(project_id, flat)
    except Exception as e:
        return response_message(str(e), 500)
    return response_message(rule)


@main.get('/api/ds/all/shahr')
def read_all_objs():
    try:
        obj = return_all_objs('ds')
    except Exception as e:
        return response_message(str(e), 500)
    return response_message(obj)


@main.get('/api/rg/all/shahr')
def read_all_rgs():
    try:
        obj = return_all_objs('rg')
    except Exception as e:
        return response_message(str(e), 500)
    return response_message(obj)


@main.get('/api/rg/<uuid:oid>/target')
def get_target(oid):
    config = return_obj(oid, 'rg')
    rg = RulesGroup()
    rg.from_dict(config)
    return response_message(rg.get_target())
