from bs4 import BeautifulSoup
import os
import math

#todo:
#put generated albums in seperate directory
#better album page
#add image alt texts
#reversed sorting 

#variables you can edit
page_size = 16
columns = 4
#make sure to edit the column width (.album-column {width: XX%;}) in the css otherwise the page may look off.

album_directory = "photos/"
album_template = "template.html"
generated_directory = "generated/"
index = "photography.html"

#metadata file, used for setting album descriptions and other stuff in the future, use "None" keyword if not used
metadata = "data.txt"

try:
    albums = os.listdir(album_directory)
except:
    print("Album directory '" + album_directory + "' Not found! Cannot continue.")
    exit()

#functions
def open_data(data):
    try:
        if data == "description":
            with open(str(album_directory + album_name + "/" + metadata), "r") as data:
                return(data.read())
    except:
        print("Metadata is enabled, but not found. Continue? y/n")
        while True:
            yn = input()
            if yn == "n":
                exit()
            elif yn == "y":
                return("")
                break
            else:
                print("Metadata file not found. Continue? y/n")

def save_page(page_number):
    try:
        #creates a file if it does not exist
        with open(str(generated_directory + album_name + str(page_number) + ".html"), "x") as generated:
            print(str("Creating a new " + album_name + str(page_number) + " gallery page"))
            generated.write(soup.prettify())
    except:
        #overwrites the existing file if found
        with open(str(generated_directory + album_name + str(page_number) + ".html"), "w") as generated:
            print(str("Overwriting " + album_name + str(page_number) + " gallery page"))
            generated.write(soup.prettify())

def add_images(page):
    image_number = 0
    column_number = 0
    images = os.listdir(str(album_directory + album_name))
    container = soup.find_all("div", class_="album")[0]
    #create columns
    for c in range(columns):
        new_column = soup.new_tag("div")
        new_column["class"] = "album-column"
        container.append(new_column)
    for i in images[(page_size * page):]:
        if i != metadata:
            image_number = image_number + 1
            column_number = column_number + 1
            #if amount of images exceeds set amount, break
            if image_number > page_size:
                break
            #this thing decides what column the image goes in
            if column_number > columns - 1:
                column_number = 0
            #create new image tags
            new_image = soup.new_tag("img", src=str("/" + album_directory + album_name + "/" + str(i)))
            new_image["class"] = "album-image"
            #find the columns and put images in column
            div = soup.find_all("div", class_=("album-column"))
            div[column_number].append(new_image)

def write_template(page):
    header = soup.find("h1")
    description = soup.find_all("p", class_="album-description")
    nav_prev = soup.find_all("a", class_="prev-album")
    nav_next = soup.find_all("a", class_="next-album")
    if metadata != None:
        album_description = open_data("description")
        for tag in description:
            tag.string = album_description
    else:
        for tag in description:
            tag.decompose()
    #set album title
    if page == None:
        header.string = album_name
    else:
        header.string = album_name + " page " + str(page + 1) + " of " + str(pages)
        pass
        #makes prev/next buttons functional
        for tag in nav_prev:
            tag["href"] = str("/" + generated_directory + album_name + str(page - 1) + ".html")
        for tag in nav_next:
            tag["href"] = str("/" + generated_directory + album_name + str(page + 1) + ".html")

    #remove prev/next buttons in navigation based on certain conditions
    if page == None:
        for tag in nav_prev:
            tag.decompose()
        for tag in nav_next:
            tag.decompose()
    elif page == 0:
        for tag in nav_prev:
            tag.decompose()
    elif page == (pages - 1):
        for tag in nav_next:
            tag.decompose()    

#generate main page with links to all albums
with open("photography.html") as template:
    soup = BeautifulSoup(template, "html.parser")
    for album_name in albums:
        links = soup.find("div")
        br = soup.new_tag("br")
        newlink = soup.new_tag("a", href=str("/" + generated_directory + album_name + "0.html"))
        newlink.string = album_name
        newlink["class"] = "album-link"
        links.append(newlink)
        links.append(br)
    try:
        with open(generated_directory + "photography.html", "x") as generated:
            #creates a file if it does not exist
            print("Creating new main page")
            generated.write(soup.prettify())
            template.close()
    except:
        with open(generated_directory + "photography.html", "w") as generated:
            #overwrites the existing file if found
            print("Overwriting main page")
            generated.write(soup.prettify())
            template.close()

#generate a gallery page for each album
for album_name in albums:
    print("-------")
    #get a list of images
    images = os.listdir(str(album_directory + album_name))
    #seeing if an album will fit in one page
    if len(images) > page_size:
        #determine how many pages are needed
        pages = math.ceil(len(images) /  page_size)
        print(album_name + " album has too many images (" + str(len(images)) + "), creating more pages (" + str(pages) + ")")
        #add set amount of images to each page
        for page in range(pages):
            print("-")
            print("Creating " + album_name + " page " + str(page))
            #open and modify the template
            try:
                with open(album_template) as template:
                    soup = BeautifulSoup(template, "html.parser")
                    write_template(page)
                    add_images(page)
                    save_page(page)
            except:
                print("Album template file '" + album_template + "' not found! Cannot continue.")
                exit()
    else:
        print(album_name + " can fit in 1 page")
        #open and modify the template
        try:
            with open(album_template) as template:
                soup = BeautifulSoup(template, "html.parser")
                write_template(None)
                add_images(0)
                save_page(0)
        except:
            print("Album template file '" + album_template + "' not found! Cannot continue.")
            exit()
print("--------------------------")
print("Done!")