import argparse
from pathlib import Path
import logging

import django
from django.core.files import File

django.setup()

from primary.models import Image

def upload_image(path: Path):
    logging.info(f"Uploading: {path}")
    filename = path.stem

    img = Image(name=filename, alt_text=filename)

    with path.open(mode='rb') as f:
        img.content = File(f, name=path.name)
        img.save()

def upload_images(path: Path):

    print("checking: " + str(path))
    for dir_entry in path.iterdir():
        print(dir_entry)
        if dir_entry.is_file():
            upload_image(dir_entry)


if __name__ == "__main__":
    print("entering")

    parser = argparse.ArgumentParser(description='Django utils for wedding site.')
    parser.add_argument('action', default = "upload_images",
                        help='Action to perform')
    parser.add_argument('--source', help='Path to working items')

    args = parser.parse_args()

    if args.action == "upload_images":
        upload_images(Path(args.source))

