#!/usr/bin/env python
# -*- coding: utf-8 -*-

import math

import fte.cDFA


class LanguageIsEmptySetException(Exception):

    """Raised when the input language results in a set that is not rankable.
    """
    pass


class IntegerOutOfRangeException(Exception):
    pass


class InvalidRegexParametersException(Exception):
    pass


class DFA(object):

    def __init__(self, cDFA, fixed_slice):
        self._cDFA = cDFA
        self.fixed_slice = fixed_slice

        self._words_in_language = self._cDFA.getNumWordsInLanguage(
            0, self.fixed_slice)
        self._words_in_slice = self._cDFA.getNumWordsInLanguage(
            self.fixed_slice, self.fixed_slice)

        self._offset = self._words_in_language - self._words_in_slice

        if self._words_in_slice == 0:
            raise LanguageIsEmptySetException()

        self._capacity = int(math.floor(math.log(self._words_in_slice, 2))) - 1

    def rank(self, X):
        """Given a string ``X`` return ``c``, where ``c`` is the lexicographical
        rank of ``X`` in the language of all strings of length ``fixed_slice``
        generated by ``regex``.
        """

        retval = self._cDFA.rank(X)

        return retval

    def unrank(self, c):
        """The inverse of ``rank``.
        """

        retval = self._cDFA.unrank(c)

        return retval

    def getCapacity(self):
        """Returns the size, in bits, of the language of our input ``regex``.
        Calculated as the floor of log (base 2) of the cardinality of the set of
        strings up to length ``fixed_slice`` in the language generated by the input
        ``regex``.
        """

        return self._capacity

    def getNumWordsInSlice(self, n):
        """Returns the number of words in the language of length ``n``"""
        return self._cDFA.getNumWordsInLanguage(n, n)
