from pathlib import Path
import zipfile
from distyctl import constants
from github import GitReleaseAsset


class FrameworkInstaller:
    def __init__(self, target_path: Path):
        self.target_path = target_path
        self.temporary_zip_path = self.target_path / constants.TEMPORARY_ZIP_BASENAME

    def install(self, framework_asset: GitReleaseAsset.GitReleaseAsset):
        self.download_framework_release(framework_asset)
        self.unzip_framework_release()
        self.cleanup()

    def download_framework_release(
        self, framework_asset: GitReleaseAsset.GitReleaseAsset
    ):
        framework_asset.download_asset(str(self.temporary_zip_path))

    def unzip_framework_release(self):
        extract_path = self.target_path / constants.FRAMEWORK_RELATIVE_PATH
        # ensure directory exists
        extract_path.mkdir(parents=True, exist_ok=True)

        with zipfile.ZipFile(
            self.target_path / constants.TEMPORARY_ZIP_BASENAME, "r"
        ) as zip_ref:
            zip_ref.extractall(extract_path)

    def cleanup(self):
        self.temporary_zip_path.unlink()
