import Cipher.tk  
from Cipher.tk import EncryptDecryptCoord, GetChiSquared, Mode

def MultiDecrypt (message, alphabet, usables = 3, lan = "English", transformations = [], lowestchi = 9999, ogMessage = ""):    
    msg = ""    
    prev = (9999, (0, 0))     # (chi, key)

    for i in range (len(message)):
        for k in range (1, len (alphabet)):
            msg = EncryptDecryptCoord(message, (i,k), alphabet, Mode.DECRYPT)
            chi = GetChiSquared (msg, lan)

            if (round (chi, 3) < round (prev[0], 3)):
                prev = (chi, (i,k))

    # base case
    if (prev[0] >= lowestchi):
        v = ogMessage
        for tr in transformations:
            v = EncryptDecryptCoord (v, tr, alphabet, Mode.DECRYPT)
            return (v, lowestchi, transformations)

    if (len(transformations) == 0):  # only set lowest chi on the first run
        lowestchi = prev[0] 
        ogMessage = message

    transformations.append (prev[1])

    return MultiDecrypt (EncryptDecryptCoord (message, prev[1], alphabet, Mode.DECRYPT), alphabet, usables, lan, transformations, prev[0], ogMessage)
             
'''
# testing do write it here
a = " abcdefghijklmnopqrstuvwxyz"
p=[]
for c in a:
    p.append (c)

print ("starting...")
print (MultiDecrypt ("dtyktckcxlbd", p))
# original 231
'''
[((29, 25, 29, 87), 'Cipher.tk.EncryptDecryptCoord', 'EncryptDecryptCoord', ({(29, 46, 29, 53): 'message', (29, 55, 29, 62): 'prev[1]', (29, 64, 29, 72): 'alphabet', (29, 74, 29, 86): 'Mode.DECRYPT'}, {}), '(message, prev[1], alphabet, Mode.DECRYPT)', False, 'from Cipher.tk import EncryptDecryptCoord, GetChiSquared, Mode\n'), ((10, 18, 10, 77), 'Cipher.tk.EncryptDecryptCoord', 'EncryptDecryptCoord', ({(10, 38, 10, 45): 'message', (10, 47, 10, 52): '(i, k)', (10, 54, 10, 62): 'alphabet', (10, 64, 10, 76): 'Mode.DECRYPT'}, {}), '(message, (i, k), alphabet, Mode.DECRYPT)', False, 'from Cipher.tk import EncryptDecryptCoord, GetChiSquared, Mode\n'), ((11, 18, 11, 42), 'Cipher.tk.GetChiSquared', 'GetChiSquared', ({(11, 33, 11, 36): 'msg', (11, 38, 11, 41): 'lan'}, {}), '(msg, lan)', False, 'from Cipher.tk import EncryptDecryptCoord, GetChiSquared, Mode\n'), ((20, 16, 20, 67), 'Cipher.tk.EncryptDecryptCoord', 'EncryptDecryptCoord', ({(20, 37, 20, 38): 'v', (20, 40, 20, 42): 'tr', (20, 44, 20, 52): 'alphabet', (20, 54, 20, 66): 'Mode.DECRYPT'}, {}), '(v, tr, alphabet, Mode.DECRYPT)', False, 'from Cipher.tk import EncryptDecryptCoord, GetChiSquared, Mode\n')]