from datetime import datetime
from pathlib import Path
from cruxpy.repo import port as cruxport


class page:
    """
    Class to handle website for portspage.
    It takes a path with ports, obtain their information.
    Then uses them with header and footer to prepare a page.

    """

    def __init__(self, path=".", header=""):

        self.ports_dir = Path(path, recursive=True)
        self.ports = sorted(list(self.ports_dir.glob("*/Pkgfile")))

        if not header:
            self.__make_header(Path(__file__).parent / "files/header.html")
        else:
            self.__make_header(Path(header))
        self.__make_table()
        self.__make_footer()

        self.content = "\n".join(self.header + self.table + self.footer)



    def __make_table(self):
        self.table = [
                '<table width="100%" cellspacing="0">',
                '<tr class="header"><td colspan="4">',
                '<strong>Signify public key:</strong> RWQXc2agtIcYBWpHqhhttRH+067uIV9sEkGPB2FT2uZRmFC712MDQF4Q</td></tr>',
                ]
        for index, port in enumerate(self.ports):
            current = "even" if index % 2 == 0 else "odd"
            p = cruxport(port)
            line = f'<tr class="{current}"><td><a href="{p.url}">{p.name}</a></td><td><a href="./{p.name}">{p.version}</a></td><td>{p.description}</td><td>{p.update}</td></tr>'
            self.table.append(line)
        self.table.append("</table>")


    def __make_header(self, file):

        with open(file) as f:
            content = f.read()
            self.header = content.splitlines()

    def __make_footer(self):
        self.footer = [
            f'<p class="footer">In total {len(self.ports)} ports',
            f'<p class="creator">Generated by portspage.py on {datetime.now()}</p>',
            "</body>",
            "</html>",
            ]


    def write(self,filepath='index.html'):
        """
        Write the page to the disk
        """
        with open(filepath,'w') as f:
            f.write(self.content)
