from __future__ import annotations

from jinja2 import Environment, FileSystemLoader
import markdown
import os

from path import Path

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from page import Page 
    from picture import Picture

env = Environment(loader=FileSystemLoader('src/templates'))
page_template = env.get_template('page.jinja')

class Page():

    def __init__(self, path: Path, name: str, pictures: list[Picture] = None, prev: Page|None = None, next: Page|None = None):
        self.name: str = name
        self._path: Path = path
        self._pictures: list[Picture] = [] if pictures is None else pictures
        self._exif: Path = Path(self._path, "exif.txt")
        self._readme: Path = Path(self._path, "readme.md")
        self._raw: Path = Path(self._path, name + ".NEF")
        self.html: Path = Path(self._path, "page.html")
        self.prev: Page = prev
        self.next: Page = next
    
    def add_picture(self, picture: Picture) -> None:
        self._pictures.append(picture)
    
    def get_picture(self) -> list[Picture]:
        return self._pictures

    def _render_raw(self):
        if not self._raw.exist():
            return None
        return self._raw.get_name()
    
    def _render_prev(self):
        if self.prev is None:
            return None
        return f"../{self.prev.name}/page.html"
    
    def _render_next(self):
        if self.next is None:
            return None
        return f"../{self.next.name}/page.html"

    def _to_html(self) -> str|None:
        print(self._pictures)
        html_rendered = page_template.render(page=self)
        return html_rendered
    
    def create(self) -> Path:
        with open(self.html.get_absolute_path(), "w") as f:
            f.write(self._to_html())
        self.created = True

    def _render_readme(self) -> str|None:
        if not self._readme.exist():
            return None
        with open(self._readme.get_absolute_path(), 'r') as f:
            text = f.read()
            html = markdown.markdown(text)
        return html

    def _gen_exif(self):
        if self._raw.exist():
            if os.system(f"exiftool {self._raw.get_absolute_path()} > {self._exif.get_absolute_path()} 2>/dev/null") == 0:
                return 0
            os.remove(self._exif.get_absolute_path())
        return 1

    def _render_exif(self) -> Path | None:
        if not self._exif.exist():
            if (self._gen_exif()):
                return None
        return self._exif.get_name()
