from rulemall.validators import Range, Unique, Regex, Length, Category
from rulemall.rules import Rule
import json
import yaml


def rule_builder(configs):
    if isinstance(configs, list):
        output = []
        for config in configs:
            output.append(config_reader(config))
    elif isinstance(configs, dict):
        return config_reader(configs)
    else:
        return TypeError


def config_reader(configs):
    name = configs.get('name')
    rules = list(map(define_rule, [config for config in configs['rules']]))
    rules = list(filter(lambda rule: rule is not None, rules))
    return {'rules': rules, 'name': name}


def define_rule(config):
    rule_type = config['rule_type']
    if rule_type == 'Range':
        validator = Range(**config['validator_parameters'])

    elif rule_type == 'Regex':
        validator = Regex(**config['validator_parameters'])

    elif rule_type == 'Length':
        validator = Length(**config['validator_parameters'])

    elif rule_type == 'Unique':
        validator = Unique(**config['validator_parameters'])

    elif rule_type == 'Category':
        validator = Category(**config['validator_parameters'])

    else:
        return None
    rule = Rule(validator=validator, **config['rule_attributes'])
    return rule
