import os
import sys


PY3 = sys.version_info[0] == 3


class ShamirSecret(object):
    """
    This performs Shamir Secret Sharing operations in an incremental way
    that is useful for PolyPasswordHasher.  It allows checking membership, genering
    shares one at a time, etc.

    Creates an object. One must provide the threshold. If you want to have it create the coefficients, etc.
    call it with secret data
    """

    def __init__(self, threshold, secretdata=None):
        self.threshold = threshold
        self.secretdata = secretdata

        self._coefficients = None

        # if we're given data, let's compute the random coefficients.   I do this
        # here so I can later iteratively compute the shares
        if secretdata is not None:
            self._coefficients = []
            for secretbyte in secretdata:
                # this is the polynomial.   The first byte is the secretdata.
                # The next threshold-1 are (crypto) random coefficients
                # I'm applying Shamir's secret sharing separately on each byte.
                if PY3:
                    secretbyte = secretbyte.to_bytes(1, "little")
                thesecoefficients = bytearray(secretbyte + os.urandom(threshold - 1))

                self._coefficients.append(thesecoefficients)

    def is_valid_share(self, share):
        """
        This validates that a share is correct given the secret data.
        It returns True if it is valid, False if it is not, and raises
        various errors when given bad data.
        """

        # the share is of the format x, f(x)f(x)
        if type(share) is not tuple:
            raise TypeError("Share is of incorrect type: {0}".format(type(share)))

        if len(share) != 2:
            raise ValueError("Share is of incorrect length: {0}".format(share))

        if self._coefficients is None:
            raise ValueError("Must initialize coefficients before checking is_valid_share")

        if len(self._coefficients) != len(share[1]):
            raise ValueError("Must initialize coefficients before checking is_valid_share")

        # let's just compute the right value
        return self.compute_share(share[0]) == share

    def compute_share(self, x):
        """
        This computes a share, given x.   It returns a tuple with x and the
        individual f(x_0)f(x_1)f(x_2)... bytes for each byte of the secret.
        This raises various errors when given bad data.
        """

        if type(x) is not int:
            raise TypeError("In compute_share, x is of incorrect type: {0}".format(type(x)))

        if x <= 0 or x >= 256:
            raise ValueError("In compute_share, x must be between 1 and 255, not: {0}".format(x))

        if self._coefficients is None:
            raise ValueError("Must initialize coefficients before computing a share")

        sharebytes = bytearray()
        # go through the coefficients and compute f(x) for each value.
        # Append that byte to the share
        for thiscoefficient in self._coefficients:
            thisshare = _f(x, thiscoefficient)
            sharebytes.append(thisshare)

        return (x, sharebytes)

    def recover_secretdata(self, shares):
        """
        This recovers the secret data and coefficients given at least threshold
        shares.   Note, if any provided share does not decode, an error is
        raised.
        """

        # discard duplicate shares
        newshares = []
        for share in shares:
            if share not in newshares:
                newshares.append(share)
        shares = newshares

        if self.threshold > len(shares):
            raise ValueError("Threshold: {0} is smaller than the number of unique shares: {1}.".format(self.threshold, len(shares)))

        if self.secretdata is not None:
            raise ValueError("Recovering secretdata when some is stored.  Use check_share instead.")

        # the first byte of each share is the 'x'.
        xs = []
        for share in shares:
            # the first byte should be unique...
            if share[0] in xs:
                raise ValueError("Different shares with the same first byte! {0!r}".format(share[0]))
            # ...and all should be the same length
            if len(share[1]) != len(shares[0][1]):
                raise ValueError("Shares have different lengths!")

            xs.append(share[0])

        mycoefficients = []
        mysecretdata = b''

        # now walk through each byte of the secret and do lagrange interpolation
        # to compute the coefficient...
        for byte_to_use in range(0, len(shares[0][1])):

            # we need to get the f(x)s from the appropriate bytes
            fxs = []
            for share in shares:
                fxs.append(share[1][byte_to_use])

            # build this polynomial
            resulting_poly = _full_lagrange(xs, fxs)

            # If I have more shares than the threshold, the higher order coefficients
            # (those greater than threshold) must be zero (by Lagrange)...
            if resulting_poly[:self.threshold] + [0] * (len(shares) - self.threshold) != resulting_poly:
                raise ValueError("Shares do not match.   Cannot decode")

            # track this byte...
            mycoefficients.append(bytearray(resulting_poly))

            # python 2 apparently had str=bytes, so using strings would make
            # sense, this is not the case with python 3, and we need to do
            # take special considerations with data types.
            if PY3:
                secret_byte = resulting_poly[0].to_bytes(1, "little")
            else:
                secret_byte = chr(resulting_poly[0])

            mysecretdata += secret_byte

        # they check out!   Assign to the real ones!
        self._coefficients = mycoefficients

        self.secretdata = mysecretdata


####################### END OF MAIN CLASS #######################

### Private math helpers... Lagrange interpolation, polynomial math, etc.

# This actually computes f(x).  It's private and not needed elsewhere...
def _f(x, coefs_bytes):
    """
    This computes f(x) = a + bx + cx^2 + ...
    The value x is x in the above formula.
    The a, b, c, etc. bytes are the coefs_bytes in increasing order.
    It returns the result.
    """
    if x == 0:
        raise ValueError('invalid share index value, cannot be 0')

    accumulator = 0

    # start with x_i = 1.   We'll multiply by x each time around to increase it.
    x_i = 1
    for c in coefs_bytes:
        # we multiply this byte (a,b, or c) with x raised to the right power.
        accumulator = _gf256_add(accumulator, _gf256_mul(c, x_i))
        # raise x_i to the next power by multiplying by x.
        x_i = _gf256_mul(x_i, x)

    return accumulator


# unfortunately, numpy doesn't seem to do polynomial arithematic over
# finite fields...   :(
#
# This helper function takes two lists and 'multiplies' them.   I only tested
# the second list is of size <=2, but I don't think this matters.
#
# for example: [1,3,4] * [4,5] will compute (1 + 3x + 4x^2) * (4 - 5x) ->
# 4 + 17x + 31x^2 + 20x^3    or [4, 17, 31, 20]
# or at least, this would be the case if we weren't in GF256...
# in GF256, this is:
# 4 + 9x + 31x^2 + 20x^3    or [4, 9, 31, 20]
def _multiply_polynomials(a, b):

    # I'll compute each term separately and add them together
    resultterms = []

    # this grows to account for the fact the terms increase as it goes
    # for example, multiplying by x, shifts all 1 right
    termpadding = []
    for bterm in b:
        thisvalue = termpadding[:]
        # multiply each a by the b term.
        for aterm in a:
            thisvalue.append(_gf256_mul(aterm, bterm))
            # thisvalue.append(aterm * bterm)

        resultterms = _add_polynomials(resultterms, thisvalue)
        # moved another x value over...
        termpadding.append(0)

    return resultterms


# adds two polynomials together...
def _add_polynomials(a, b):

    # make them the same length...
    if len(a) < len(b):
        a = a + [0]*(len(b)-len(a))
    if len(a) > len(b):
        b = b + [0]*(len(a)-len(b))

    assert(len(a) == len(b))

    result = []
    for pos in range(len(a)):
        # result.append(a[pos] + b[pos])
        result.append(_gf256_add(a[pos], b[pos]))

    return result


# For lists containing xs and fxs, compute the full Lagrange basis polynomials.
# We want it all to populate the coefficients to check the shares by new
# share generation
def _full_lagrange(xs, fxs):
    assert(len(xs) == len(fxs))

    returnedcoefficients = []
    # we need to compute:
    # l_0 =  (x - x_1) / (x_0 - x_1)   *   (x - x_2) / (x_0 - x_2) * ...
    # l_1 =  (x - x_0) / (x_1 - x_0)   *   (x - x_2) / (x_1 - x_2) * ...
    for i in range(len(fxs)):

        this_polynomial = [1]
        # take the terms one at a time.
        # I'm computing the denominator and using it to compute the polynomial.
        for j in range(len(fxs)):
            # skip the i = jth term because that's how Lagrange works...
            if i == j:
                continue

            # I'm computing the denominator and using it to compute the polynomial.
            denominator = _gf256_sub(xs[i], xs[j])
            # denominator = xs[i]-xs[j]

            # don't need to negate because -x = x in GF256
            this_term = [_gf256_div(xs[j], denominator), _gf256_div(1, denominator)]
            # this_term = [-xs[j]/denominator, 1/denominator]

            # let's build the polynomial...
            this_polynomial = _multiply_polynomials(this_polynomial, this_term)

        # okay, now I've gone and computed the polynomial.   I need to multiply it
        # by the result of f(x)

        this_polynomial = _multiply_polynomials(this_polynomial, [fxs[i]])

        # we've solved this polynomial.   We should add to the others.
        returnedcoefficients = _add_polynomials(returnedcoefficients, this_polynomial)