from PIL import Image
import glob
import re
import os
from datetime import date

currentdir = "/Users/normrasmussen/Documents/Work/Scripts/Auto_Scrape_Screenshots/"

def find_pictures(currentdir):
    files = []
    listfiles = glob.glob(currentdir + "*.png")
    for file in listfiles:
        files.append(os.path.basename(file))
        # Now file will only show the file name, not the entire path
    split_resources(files, currentdir)


def split_resources(files, currentdir):
    try:
        resource_title = files[0]
        resource_title = resource_title[:-6]
        files.sort()
        new_list = []
        for file in files:
            if resource_title in file:
                new_list.append(file)
        for item in new_list:
            files.remove(item)
        split_resources(files, currentdir)
        process_pictures(new_list, resource_title, currentdir)
    except IndexError as e:
        print(e)
    finally:
        pass


def process_pictures(new_list, resource_title, currentdir):
    resource_title = re.sub(r'[?]', "", resource_title)
    today = date.today()
    today = today.strftime("%m.%d.%Y")
    image_list = []
    resource = Image.open(new_list[0])
    resource = resource.convert("RGB")
    for picture in new_list[1:]:
        image = Image.open(picture)
        converted = image.convert("RGB")
        image_list.append(converted)
        # image_list.append(image)
    resource.save(
        currentdir + f"PDFs/{resource_title}_{today}.pdf",
        save_all=True,
        append_images=image_list,
    )


def delete_originals(currentdir):
    path = glob.glob(currentdir + "*.png")
    for file in path:
        try:
            os.remove(file)
        except TypeError as e:
            print("Error!")
            print(e)
        finally:
            print("All Done")


if __name__ == "__main__":
    find_pictures(currentdir)
    delete_originals(currentdir)
