# First, get the images using:
#   wget --recursive --no-clobber --no-parent --no-check-certificate --accept '*-v.jpg' --no-cookies --no-dns-cache -e robots=off --domains=coin-database.com -P $PWD https://www.coin-database.com


import os
from PIL import Image, ImageDraw

OUTPUT_DIR = 'prepared'

if not os.path.exists(OUTPUT_DIR):
  os.mkdir(OUTPUT_DIR)

image_paths = []
for root, dirs, files in os.walk(os.getcwd()):
    for file in files:
        if file.endswith('.jpg'):
            image_paths.append(os.path.join(root, file))


i = 0
for image_path in image_paths:
    with Image.open(image_path).convert('L') as img:
        width, height = img.size
        
        # Uncomment to try and flood-fill the background.
        # ImageDraw.floodfill(img, (1,1), 0, thresh=99)
        # ImageDraw.floodfill(img, (width-1,1), 0, thresh=25)
        # ImageDraw.floodfill(img, (1,height-1), 0, thresh=25)
        # ImageDraw.floodfill(img, (width-1,height-1), 0, thresh=25)

        if width / height > 1.5:
            left_half = img.crop((0, 0, width/2, height))
            right_half = img.crop((width/2, 0, width, height))
            left_half.save('prepared/{}.jpg'.format(i))
            i = i + 1
            right_half.save('prepared/{}.jpg'.format(i))
            i = i + 1
            continue

        if height / width > 1.5:
            top_half = img.crop((0, 0, width, height/2))
            bottom_half = img.crop((0, height/2, width, height))
            top_half.save(os.path.join(OUTPUT_DIR, '{}.jpg'.format(i)))
            i = i + 1
            bottom_half.save(os.path.join(OUTPUT_DIR, '{}.jpg'.format(i)))
            i = i + 1
            continue

        img.save(os.path.join(OUTPUT_DIR, '{}.jpg'.format(i)))
        i = i + 1