import glob
import os
from .pages import GalleryPage, DetailPage
import shutil
from pathlib import Path
import importlib.resources as pkg_resources
from .. import assets
import zipfile


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

    def build(self):
        gallery_paths = glob.glob(self.source_dir + "**/")
        relative_sources = [os.path.relpath(g_path, self.source_dir) for g_path in gallery_paths]

        for gallery in relative_sources:
            # ensure destination exists
            destination_path = os.path.join(self.output_dir, gallery)
            os.makedirs(destination_path, exist_ok=True)
            gpage = GalleryPage(gallery, destination_path)
            gpage.build()

        # HACK: copy the CSS file after the above has ensured directory existence
        shutil.copy(
            pkg_resources.path(assets, "main.css"),
            self.output_dir
        )

        with zipfile.ZipFile(pkg_resources.path(assets, "bootstrap-5.0.2-dist.zip"), 'r') as bs_dist:
            bs_dist.extractall(self.output_dir)
