import sys
import shutil
import os
from progress.bar import Bar

from path import Path
from picture import Picture
from page import Page
from album import Album
import config

def argument_parsing():
    if (len(sys.argv) < 2):
        print("error: missing argument", file=sys.stderr)
        exit(1)
    return sys.argv[1]

def scan_pages(folders: list[Path]) -> list[Page]:
    pages: list[Page] = []
    prev: Page = None
    with Bar("Scanning Pages...", max=len(folders)) as bar:
        for folder in folders:
            files: list[Path] = folder.get_files()

            page: Page = Page(folder, folder.get_name(), prev=prev)

            raw: Path = Path(folder, folder.get_name() + ".NEF")
            for file in files:
                if file.get_name().endswith(".png"):
                    page.add_picture(Picture(file, page=page, raw=raw))

            if len(page.get_pictures()) == 0:
                bar.next()
                continue

            pages.append(page)
            if prev is not None:
                prev.next = page
            prev = page

            bar.next()
    pages[-1].next = pages[0]
    pages[0].prev = pages[-1]
    return pages

def create_pages(pages: list[Page]) -> None:
    with Bar("Generating Pages...", max=len(pages)) as bar:
        for page in pages:
            page.create()
            bar.next()

def scan_albums(pages: list[Page], albums_path: Path) -> list[Album]:
    albums: dict[str, Album] = {}
    with Bar("Scanning pages...", max=len(pages)) as bar:
        for page in pages:
            for picture in page.get_pictures():
                for album_name in picture.get_albums_name():
                    album: Album | None = albums.get(album_name)
                    if (album is None):
                        album = Album(album_name, albums_path)
                        albums.update({album_name: album})
                    album.add_picture(picture)
            bar.next()
    return (albums.values())

def create_albums(albums: list[Album]) -> None:
    with Bar("Generating albums...", max=len(albums)) as bar:
        for album in albums:
            album.create()
            bar.next()


def main():
    site_path = Path(argument_parsing())
    pages: list[Page] = scan_pages(site_path.get_dirs())
    shutil.copy2("./src/templates/page.css", site_path.get_absolute_path())
    create_pages(pages)
    album_path: Path = Path(site_path, "albums")
    if (not album_path.exist()):
        album_path.create()
    albums: list[Album] = scan_albums(pages, album_path)
    create_albums(albums)
    if config.CREATE_GENERAL_ALBUM:
        shutil.move(os.path.join(album_path.get_absolute_path(), "general.html"), os.path.join(site_path.get_absolute_path(), "index.html"))
    shutil.copy2("./src/templates/album.css", site_path.get_absolute_path())

if __name__ == "__main__":
    main()
