import requests
import json
from PIL import Image, ImageOps
import imagehash
from io import BytesIO

DATABASE_FILE = "card_database.json"

ERROR_FILE = "failed_cards.json"

#location to draw database: https://api.tcgdex.net/v2/en/cards or a single set 
API_LOCATION = "https://api.tcgdex.net/v2/en/cards"

# Image extension tpye. Can be: high.jpg, high.png, low.jpg, low.png
IMAGE_TYPE = "high.png"


def compute_hashes_for_image(img):
    """Return hashes for all 4 orientations."""
    # Normal
    img_norm = img
    # Mirrored
    img_mir = ImageOps.mirror(img)
    # Upside down
    img_ud = ImageOps.flip(img)
    # Upside down mirrored
    img_udmir = ImageOps.flip(img_mir)

    orientations = [img_norm, img_mir, img_ud, img_udmir]

    # For each orientation compute: aHash, wHash, pHash, dHash
    avghashes = []
    whashes = []
    phashes = []
    dhashes = []

    for im in orientations:
        avghashes.append(int(str(imagehash.average_hash(im)), 16))
        whashes.append(int(str(imagehash.whash(im)), 16))
        phashes.append(int(str(imagehash.phash(im)), 16))
        dhashes.append(int(str(imagehash.dhash(im)), 16))

    return avghashes, whashes, phashes, dhashes

def build_database():
    database = {}
    failed = {}

    response = requests.get(API_LOCATION)
    
    data = response.json()

    for card in data:
        card_id = card["id"]

        if "image" in card:
            card_image_url = card["image"] + f"/{IMAGE_TYPE}"

            symbol_image = requests.get(card_image_url)

            # Saves cards that didnt return and image from the URL and could not be added to the database
            if symbol_image.status_code == 404:
                failed[card_id] = {
                    "reason": "404 not found"
                }

            img = Image.open(BytesIO(symbol_image.content)).convert("RGB")

            avgh, wh, ph, dh = compute_hashes_for_image(img)

            database[card_id] = {
                "avghashes": avgh,
                "whashes": wh,
                "phashes": ph,
                "dhashes": dh,
            }

        else: # Saves cards that didnt have and image and could not be added to the database
            failed[card_id] = {
                "reason": "no image"
            }
        
        print("Card ID: " + card_id)

    with open(DATABASE_FILE, "w") as f:
        json.dump(database, f)

    with open(ERROR_FILE, "w") as f:
        json.dump(failed, f)

    print(f"Database created with {len(database)} cards")
    

build_database()