#!/usr/bin/env python
# -*- coding: utf8 -*-

from BitVector import BitVector
import math
import re

from GenericFile import GenericFile

class ZIFile (GenericFile):

    name = "Zbiór Implikantów"
    extension = 'ZI'

    def __init__(self, content=None):
        GenericFile.__init__(self, content)

        if content is not None:
            self.init_from_content(content)

    def init_from_content(self, content):
        self._function = []

        for result, arg in zip(content, range( \
                int(len(content)), -1, -1)):
            if result == 1:
                bv = BitVector(intVal=arg, size=self.args)
                self._function.append([bit for bit in bv])



    def parse_body(self, content):
        self._function = []
        for line in content:
            if not re.compile('^[\-\da-zA-Z]{' + str(self.args) +
                    '}$').match(line):
                #TODO: Exception - bad line
                pass

            self._function.append([self.char_to_value(char) \
                    for char in line])

    def prepare_body(self):
        result = ""

        for line in self._function:
            for value in line:
                result += self.value_to_char(value)
            result += '\n'

        return result

    def calculate_function(self, args):
        result = 0

        for implicant in self._function:
            tmp = 1
            for mask, value in zip(implicant, args):
                if mask != self.char_to_value('-'):
                    if mask == 1:
                        tmp *= value
                    else:
                        tmp *= not value
            result |= tmp

        return result

