from .exceptions import MalformedIndexConditionException, MalformedIndexException


class Index:

  def __init__(self, *fields):
    if not fields:
      raise MalformedIndexException('An index must have at least one field')
    self.fields = fields
    self.filter = {}

  def _chain(self, operator, operand):
    if isinstance(operand, Index):
      raise MalformedIndexConditionException('Cannot compare two indexes')
    if len(self.filter) == 2:
      raise MalformedIndexConditionException('Cannot chain more than two comparisons')
    if operator in self.filter:
      raise MalformedIndexConditionException('Cannot chain identical operators')
    self.filter[operator] = operand if type(operand) is tuple else (operand,)
    return self

  def __lt__(self, operand):
    return self._chain('<', operand)

  def __le__(self, operand):
    return self._chain('<=', operand)

  def __gt__(self, operand):
    return self._chain('>', operand)

  def __ge__(self, operand):
    return self._chain('>=', operand)

  def __eq__(self, operand):
    return self._chain('==', operand)

  def __ne__(self, operand):
    return self._chain('!=', operand)


class ComputedIndexField:

  def __init__(self, field, fn):
    self.field = field
    self.fn = fn
