# -*- coding: utf-8 -*-
from presentation import RGBColors
from slides_config import slides_config


def get_fill_color(rules, value):
    try:
        value = float(value)
        get_color = get_color_by_num
    except ValueError:
        value = unicode(value).strip().lower()
        get_color = get_color_by_bool

    if rules.get('no_format'):
        fill_color = RGBColors['white']

    else:
        fill_color = get_color(rules, value)
        if not fill_color:
            fill_color = RGBColors['white']

    if type(value) == float:
        value = ('%.0f%%' % (value * 100.)).replace('.', ',')

    return fill_color, unicode(value)


def get_color_by_bool(rules, value):
    for color_name, v in rules.iteritems():
        if v == value:
            return RGBColors[color_name]


def get_color_by_num(rules, value):
    for color_name, bounds in rules.iteritems():
        if check_num_rule(bounds, round(value, 2)):
            return RGBColors[color_name]


def check_num_rule(bounds, value):
    equal = bounds.get('equal')
    if equal:
        if value == equal['value']:
            return True
        else:
            return False

    l_bound = bounds.get('higher')
    if l_bound:
        l_flag = value >= l_bound['value'] if l_bound.get('include', True) else value > l_bound['value']

    else:
        l_flag = True

    u_bound = bounds.get('lower')
    if u_bound:
        u_flag = value <= u_bound['value'] if u_bound.get('include', True) else value < u_bound['value']

    else:
        u_flag = True

    return min(l_flag, u_flag)


def get_fill_rules(data_name, value):
    rules_yml = slides_config('rules')
    try:
        value = float(value)
        r_key = 'num_bounds'
    except ValueError:
        r_key = 'boolean'

    if rules_yml.get(data_name):
        return rules_yml[data_name].get(r_key, rules_yml[data_name])
    else:
        return rules_yml['def_rules'][r_key]
