import os
from .html_blocks import *
from .detail_page import DetailPage
from ..utils import filesByExtension, _findCaptionFile
from pathlib import Path
from ...image_resizer import resizeImage


class GalleryElement:
    def __init__(self, source_path, out_dir, thumb_dir, big_dir):
        self.source_path = source_path
        self.out_dir = out_dir

        self.big_truepath = os.path.join(big_dir, os.path.basename(self.source_path))
        self.big_relpath = os.path.relpath(self.big_truepath, Path(self.out_dir).parent)

        self.thumb_truepath = os.path.join(thumb_dir, os.path.basename(self.source_path))
        self.thumb_relpath = os.path.relpath(self.thumb_truepath, Path(self.out_dir).parent)

        self.basename = os.path.splitext(os.path.basename(self.source_path))[0]
        caption_file = _findCaptionFile(os.path.dirname(source_path), self.basename)
        self.detail_page = DetailPage(caption_file, source_path, self.big_relpath, self.out_dir)        

    def renderHTML(self) -> str:
        return GALLERY_ELEMENT_BLOCK.format(
                image_path="/" + self.big_relpath,
                image_thumb_path="/" + self.thumb_relpath,
                image_name=self.basename.replace("_", " "),
        )

    def generateFiles(self) -> None:
        self.detail_page.build()
        resizeImage(self.source_path, self.thumb_truepath, 800)
        resizeImage(self.source_path, self.big_truepath, 2000)


class GalleryPage:
    def __init__(self, source_dir, output_dir):
        self.source_dir = source_dir
        self.output_dir = output_dir

    def build(self) -> None:
        print(f"Building gallery {self.source_dir} -> {self.output_dir}")

        thumbnail_directory = os.path.join(self.output_dir, "thumbs")
        big_directory = os.path.join(self.output_dir, "bigs")
        os.makedirs(thumbnail_directory, exist_ok=True)
        os.makedirs(big_directory, exist_ok=True)

        gallery_html = ""
        gallery_html += HTML_HEADER
        gallery_html += '<div class="gallery_container"><ul>'

        for image_source in filesByExtension(self.source_dir, "JPG"):
            element = GalleryElement(image_source, self.output_dir, thumbnail_directory, big_directory)
            gallery_html += element.renderHTML()
            element.generateFiles()

        gallery_html += '<li></li></ul>'

        with open(os.path.join(self.output_dir, "index.html"), 'w') as gallery_file:
            gallery_file.write(gallery_html)
