import os

from .page import Page

class TreePage(Page):
    def __init__(self, out_dir, name, commit, sub_tree, repo, content_subdir):
        super(TreePage, self).__init__('tree.md', out_dir, os.path.join(commit.hexsha, 't', sub_tree, 'index.md'), name, content_subdir)
        self.tree = commit.tree.join(sub_tree) if sub_tree else commit.tree
        self.repo = repo
        self.commit = commit
        self.sub_tree = sub_tree

    def _generate_entries(self, nodes):
        entries = []
        for node in nodes:
            latest_commit = next(self.repo.iter_commits(self.commit, max_count=1, paths=node.path))
            entry = {
                'name': node.name + str('/' if node.type == 'tree' else ''),
                'modified': latest_commit.committed_datetime
            }
            entries.append(entry)
        return entries

    def _get_entries(self):
        files = self._generate_entries(self.tree.blobs)
        dirs = self._generate_entries(self.tree.trees)
        files.sort(key=lambda x: x['name'])
        dirs.sort(key=lambda x: x['name'])
        return dirs + files

    def context(self):
        return {
            'entries': self._get_entries(),
            'title': self.name + ': Tree'
        }

    def build_pages(self, factory):
        visited = set()
        remaining = [self.sub_tree]
        tree_pages = []
        while remaining:
            current = remaining.pop()
            if not current in visited:
                visited.add(current)
                tree = self.commit.tree.join(current) if current else self.commit.tree
                tree_pages.append(factory.new_tree(self.commit, tree.path, self.repo))
                for sub_tree in tree.trees:
                    remaining.append(sub_tree.path)

        return tree_pages

