import  re, random

class DirectEncodeDecode():

    def __init__(self, window_size=1, start_marker='#', end_marker='#'):
        self.window_size = window_size
        # self.pattern_regex = r""+start_marker+"[0-9]{1}[a-zA-Z0-9-.:]{1,}"+end_marker
        self.pattern_regex = r""+start_marker+"[0-9]{1,},[a-zA-Z0-9-.:]{1,}"+end_marker
        self.pattern = re.compile(self.pattern_regex)


    def has_pattern(self, input):
        matchedStrings = self.pattern.findall(input)
        if len(matchedStrings) > 0:
            return True, matchedStrings
        return False, []

    def encode(self, secretMessage):
        # convert secretMessage into binary
        a_bytes = bytes(secretMessage, "ascii")
        binaryArray = []
        for byte in a_bytes:
            binaryArray.append("{0:b}".format(byte).rjust(8,'0'))
        binaryFakeDNA = ''.join(binaryArray)

        # using dictionary convert cover dna to binary
        dnaDictionary = {'A':'00', 'C':'01', 'G':'10', 'T':'11'}
        reverseDnaDictionary = dict((v,k) for k,v in dnaDictionary.items())
        fakeDNA = ""
        for i in range(0, len(binaryFakeDNA), 2):
            fakeDNA += reverseDnaDictionary[binaryFakeDNA[i:i+2]]
        return fakeDNA

    def decode(self, fakeDNA):
        # convert fake dna to binary using dictionary
        dnaDictionary = {'A':'00', 'C':'01', 'G':'10', 'T':'11'}
        binaryOfFakeDNA = ""
        for base in fakeDNA:
            binaryOfFakeDNA += dnaDictionary[base]
        # convert binary to ascii and reveal message
        bytes = [binaryOfFakeDNA[i:i+8] for i in range(0, len(binaryOfFakeDNA), 8)]
        decodeMessage = ""
        for byte in bytes:
            decodeMessage += chr(int(byte, 2))
        bases = ['A', 'C', 'T', 'G']
        # return bases[random.randint(0,3)]+decodeMessage+bases[random.randint(0,3)]
        return decodeMessage

    def findingPayload(self, input_DNA_sequence):
        # moving the payload by window size
        payload_parts = []
        for i in range(0, len(input_DNA_sequence), self.window_size):
            fakeDNA = input_DNA_sequence[i:]
            decodeMessage = self.decode(fakeDNA)
            gotPattern, values = self.has_pattern(decodeMessage)
            if gotPattern:
                payload_parts.extend(values)
        return payload_parts


