# organize_photos.py
#
# author: deng
# date  : 20240121

from shutil import move
from pathlib import Path
from pathlib import PosixPath
from argparse import ArgumentParser

import exifread
from rich.progress import track


def main(image_dir: PosixPath, extensions: str) -> None:
    """Gather photos by their created dates

    Args:
        image_dir (PosixPath): dir of images
        extensions (str): extensions of photo
    """
    image_paths = [path for path in image_dir.glob(extensions) if path.is_file()]

    for image_path in track(image_paths, 'Move images ...'):

        with open(image_path, 'rb') as f:
            exif_data = exifread.process_file(f)

        try:
            image_datetime = exif_data['Image DateTime']
        except KeyError:
            print(f'Can not find ImageDateTime tag on this image: {image_path}')
            continue

        image_date, _ = str(image_datetime).split()
        image_date = image_date.replace(':', '-')
        image_date_dir = image_dir.joinpath(image_date)
        if not image_date_dir.is_dir():
            image_date_dir.mkdir()
            print(f'Dir created: {image_date_dir}')

        src = image_path
        dst = image_date_dir.joinpath(image_path.name)
        move(src=src, dst=dst)


if __name__ == '__main__':

    parser = ArgumentParser()
    parser.add_argument('-i', '--image_dir', help='Your image dir', type=str)
    parser.add_argument('-e', '--extensions', help='Image extensions', type=str)
    args = parser.parse_args()
    image_dir = args.image_dir
    extensions = args.extensions

    if not image_dir:
        # for pyinstaller use case
        image_dir = Path(__file__).parent.parent
    else:
        image_dir = Path(image_dir)

    if not extensions:
        extensions = '*.[pPjJrRhHoO][nNpPaAeErR][gGeEwWiIfF]*'

    main(image_dir=image_dir, extensions=extensions)
