from PIL import Image
import requests
import base64
from io import BytesIO

modeles = "invaders_exemple01.png"
modeles_solution = "DAAHEADBBHEBGIAFFIFAGIGB"

url_get = "https://pydefis.callicode.fr/defis/C22_Invaders01/get/Cavogrenier/bb052"
url_post = "https://pydefis.callicode.fr/defis/C22_Invaders01/post/Cavogrenier/bb052"

def convert_b_and_w(image):
    """Convert the img to black and white"""
    img = Image.open(image)
    width, height = img.size
    res = Image.new("1", (width, height))
    for y in range(height):
        for x in range(width):
            pixel = img.getpixel((x,y))
            if pixel == (0, 0, 0):
                res.putpixel((x,y), 0)
            else:
                res.putpixel((x,y), 1)
    return res

def get_image_fingerprint(img):
    width, height = img.size
    res = []
    for y in range(height):
        for x in range(width):
            res.append(str(img.getpixel((x,y))))
    return "".join(res)

convert_b_and_w(modeles)

img_modeles = convert_b_and_w(modeles)

width_modeles, height_modeles = img_modeles.size
width_modele = width_modeles // 6
height_modele = height_modeles // 4

#Learn from modeles
offset = 0
mods = {}
for y in range(4):
    for x in range(6):
        tmp = img_modeles.crop((x*width_modele, y*height_modele, (x+1)*width_modele, (y+1)*height_modele))
        mods[get_image_fingerprint(tmp)] = modeles_solution[offset]
        #print(modeles_solution[offset],get_image_fingerprint(tmp))
        offset = offset + 1


res = requests.get(url_get)
sig = res.text.splitlines()[0]
contents = "".join(res.text.splitlines()[1:]).replace("\r", "").replace("\n", "")

screen = convert_b_and_w(BytesIO(base64.b64decode(contents)))

solution = ""
for y in range(4):
    for x in range(6):
        tmp = get_image_fingerprint(screen.crop((x*width_modele, y*height_modele, (x+1)*width_modele, (y+1)*height_modele)))
        if tmp in mods:
            solution = solution + mods[tmp]
        else:
            solution = solution + "C"

print(solution)

param = {'sig':sig, 'rep':solution}
res = requests.post(url_post, verify=False, data=param)

print(res)
print(res.text)

screen.show()
