#!/usr/bin/env python
# -*- coding: utf8 -*-
from math import log
from BitVector import BitVector
from numpy import *

from GenericFile import GenericFile

class WTChecker(GenericFile):
    name = "Transformata Walsha"

    def __init__(self, content=None):
        if content is None:
            #TODO: Rzucić coś
            return None

        if (len(content) % 2) != 0:
            #TODO: Musi być parzyste
            return None

        GenericFile.__init__(self, content)

        #self.init_from_content(self.convert_to_polar(content))
        self.init_from_content(content)
    
    def _get_h_val(self, x, y, size):
        size = BitVector(intVal=size)
        x = BitVector(intVal=x, size=size.size)
        y = BitVector(intVal=y, size=size.size)
        ret = 0
        for s in xrange(size.size):
            ret = ret ^ (x[s]*y[s])
        return ret

    def _create_h_table(self, content):
        self.htable = []
        flen = len(content)
        self.htable = empty((flen, flen), int)
        for x in xrange(flen):
            for y in xrange(flen):
                self.htable[x][y] = self._get_h_val(x, y, flen) ^ content[y]
        
    
    def init_from_content(self, content):
        self._create_h_table(content)
        tsize = len(content)
        self._function = str(content)
        self._function += "\n"
        self._function += str(self.htable)
        self._function += "\n"
        max = 0
        maxtab = empty(tsize, int)
        for x in xrange(tsize):
            tmpmax = 2**self.args
            xnum = 0
            for y in xrange(tsize):
                xnum += self.htable[x][y]
            tmpmax = tmpmax - (2*xnum)
            maxtab[x] = tmpmax
            if tmpmax > max: max=tmpmax
        self._function += str(maxtab)
        self._function += "\n"
        self._function += "\n"
        self.calculate_nonlinearity(tsize, max)


    def calculate_nonlinearity(self, size, max):
        self.nonlinearity = (size - max) / 2
        self._function += "(%d - %d) / 2 = %d" % \
            (size, max, self.nonlinearity)

    def change_to_printable(self, function):
        self._function = ""

        for line in function:
            for value in line:
                if value >= 0:
                    self._function += ' '
                self._function += str(value) + '   '
            self._function += '\n'


    def parse_out(self):
        return self._function

