import requests
import os
import time

url_get = "https://pydefis.callicode.fr/defis/MLPotter01/intern/aMI7JVIH+mN1UYdaODx1mtD6QQVrpTvKjVyFbfcqBW9gwm1qWxv4LTI%3D/card.png"
url_post = "https://pydefis.callicode.fr/defis/MLPotter01/intern/aMI7JVIH+mN1UYdaODx1mtD6QQVrpTvKjVyFbfcqBW9gwm1qWxv4LTI%3D/reponse"

card_folder = os.path.join(os.path.dirname(__file__), "chocogrenouille")

ctr = 0

#Preload already dopwnloaded cards
cards = {}
for (dirpath, dirnames, filenames) in os.walk(card_folder):
    for filename in filenames:
        with open(os.path.join(card_folder, filename), mode='rb') as file_obj:
            cards[file_obj.read()] = filename.replace(".png", "")
    break

while True:
    req_card = requests.get(url = url_get)

    if req_card.content in cards:
        name = cards[req_card.content]
        found = True
    else:
        name = "unknown"
        found = False

    req_res = requests.get(url = f"{url_post}/{name}")

    response = req_res.content.decode("utf-8").strip().replace('"', '')

    if "Password" in response:
        print(f"La reponse est: {response}")
        break

    if found and response == name:
        ctr = ctr + 1
        print(f"J'ai bon: '{name}' ({ctr})")
    elif found:
        ctr = 0
        print(f"J'ai pas bon: '{response}' alors que j'avais prévu '{name}'")
    else:
        ctr = 0
        print(f"Un nouveau venu: '{response}'")

    if not found:
        cards[req_card.content] = response
        with open(os.path.join(card_folder, response+".png"), "wb") as binary_file:
            # Write bytes to file
            binary_file.write(req_card.content)

    time.sleep(1.1)
