# By: Riasat Ullah
# This class represents a single routing rule.

from utils import var_names
import re


class RoutingRule(object):

    def __init__(self, rule_type, field_name, comparator, expected_value):
        self.rule_type = rule_type
        self.field_name = field_name
        self.comparator = comparator
        self.expected_value = expected_value

    def equals(self, given_value):
        '''
        Checks if a given value equals the expected value.
        :param given_value: the given value
        :return: True if it equals; False otherwise
        '''
        if isinstance(given_value, bool):
            if str(given_value).lower() == self.expected_value.lower():
                return True
        else:
            if isinstance(self.expected_value, str) and\
                    (isinstance(given_value, int) or isinstance(given_value, float)):
                given_value = str(given_value)
            if given_value == self.expected_value:
                return True
        return False

    def contains(self, given_value):
        '''
        Checks if a given value contains the expected value.
        :param given_value: the given value
        :return: True if it contains; False otherwise
        '''
        try:
            if self.expected_value in given_value:
                return True
        except TypeError:
            raise
        return False

    def matches(self, given_value):
        '''
        Checks if a given values matches the expected regex pattern.
        :param given_value: the given value
        :return: True if it matches; False otherwise
        '''
        if isinstance(given_value, str):
            match = re.search(self.expected_value, given_value)
            if match:
                return True
        return False

    def to_dict(self):
        '''
        Gets the dict of the Routing rule object.
        :return: dict of the RoutingRule
        '''
        data = {
            var_names.rule_type: self.rule_type,
            var_names.field_name: self.field_name,
            var_names.comparator: self.comparator,
            var_names.field_value: self.expected_value
        }
        return data
