import os, sys, random
import argparse
from datetime import date
from time import strftime
from pathlib import Path

import cv2
from PIL import Image, ImageDraw

parser = argparse.ArgumentParser(description='Process an image uploaded to the server.')
parser.add_argument('filename', action='store',
                    help='Filename of photo to process')
parser.add_argument('city', action='store',
                    help='City of the visitor')
parser.add_argument('school', action='store',
                    help='School of the visitor')
parser.add_argument('age', action='store',
                    help='Age of the visitor')

args = parser.parse_args()

image = cv2.imread(args.filename)
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier("./data/haarcascade_frontalface_default.xml")
faces = face_cascade.detectMultiScale(image_gray)

if (len(faces) != 1):
    print(f"Error: {len(faces)} faces detected in the image.")
    sys.exit(1)

im = Image.open(args.filename)
draw = ImageDraw.Draw(im)

randomFile = random.choice(os.listdir("./data/circles"))
circle = Image.open(f"./data/circles/{randomFile}")

for x, y, width, height in faces:
    circle = circle.resize((width * 2, height * 2), Image.ANTIALIAS)
    im.paste(circle, (x - width // 2, y - height // 2 ), circle)

date = date.today()
time = strftime("%H-%M-%S")

Path(f"./processed/{date}/").mkdir(parents=True,exist_ok=True)
im.save(f"./processed/{date}/{time}.jpg")

sys.exit(0);
