import markdown
from .html_blocks import *
from ...image_resizer import resizeImage
from ...exif import generate_exif_dict
import os


class DetailPage:
    def __init__(self, caption_source, image_source_path, image_asset_path, output_dir):
        self.caption_source = caption_source
        self.output_dir = output_dir
        self.image_source_path = image_source_path
        self.image_asset_path = image_asset_path

    def build(self) -> None:
        html = ""
        html += HTML_HEADER
        basename: str = os.path.splitext(os.path.basename(self.caption_source))[0]

        with open(self.caption_source, 'r') as caption_file:
            caption_html = markdown.markdown(caption_file.read())

        exif_data = generate_exif_dict(self.image_source_path)

        exposure_info_table = EXPOSURE_INFORMATION_BLOCK.format(
            shutter_speed=f"{exif_data['ExposureTime']['processed']}",
            aperture=exif_data['FNumber']['processed'],
            focal_length=exif_data['FocalLength']['processed'],
            iso=exif_data['ISOSpeedRatings']['processed'],
            lens_model=exif_data['LensModel']['processed'],
            camera_model=exif_data['Model']['processed']
        )

        html += GALLERY_DETAIL_BLOCK.format(
            image_path="/" + self.image_asset_path, 
            image_name=basename.replace("_", " "),
            exposure_details=exposure_info_table,
            caption=caption_html
        )

        html += "</body></html>"

        with open(os.path.join(self.output_dir, f"{basename}_details.html"), 'w') as detail_file:
            detail_file.write(html)