import os

from .get import get_bucket_layout
from .generator import generate
from .upload import upload


class _Builder:
    """
    Takes all the classes and combines them to create and upload files to s3 bucket
    """

    def __init__(self) -> None:
        self.packages = []

    def _run(self, bucket):
        """
        starting point of class
        """
        self.bucket_name = bucket
        ### CHECK BUCKET NAME HERE!! SHOULD match (bucket.com) or (xxx.bucket.com) ###
        ### if s3:// given remove before continuing ###
        self.layout = get_bucket_layout(self.bucket_name)
        self._bucket_loop()

    def _create_key(self, path):
        """
        takes a path as input and joins it with "index.html" to create the
        desired s3 bucket key.
        """
        return os.path.join(path, "index.html")

    def _bucket_loop(self):
        """
        Loops through the dictionary returned by get_bucket_layout().
        Inside the loop we call the generate() method te create the
        desired HTML for the index page. This recurses into all directories
        inside the bucket. Every directory is given an index.html file that
        has been programmatically created from names of objects inside the
        bucket which is then uploaded to the bucket.
        """
        # loops through each package
        # append self.packages with each package name

        for name in self.layout.keys():
            self.packages.append(name)

            # generate package index
            self.gen_package = generate(
                title=name,
                header=name,
                links=self.layout[name]["files"],
            )

            # get bucket path
            upload(self.bucket_name, self.gen_package, name)
            # print(self.gen_package)

            # generate version index
            # for version in self.layout[name]["versions"]:
            #     self.files = [
            #         file for file in self.layout[name]["files"] if version in file
            #     ]

            #     self.gen_version = generate(
            #         title=name,
            #         header=f"""{name} - {version}""",
            #         links=self.files,
            #     )

            #     # get bucket path
            #     upload(self.bucket_name, self.gen_version, os.path.join(name, version))
            #     # print(self.gen_version)

        # generate root index
        self.gen_root = generate(
            title=self.bucket_name,
            header=self.bucket_name,
            links=self.packages,
        )
        # get bucket path
        upload(self.bucket_name, self.gen_root, "")
        # print(self.gen_root)


_builder = _Builder()


def build(bucket):
    """
    The public method for the _Builder class
    """
    return _builder._run(bucket)


if __name__ == "__main__":
    build("pip.trainland.io")
