import datetime
import os
from io import StringIO
from pathlib import Path

project_blacklist = ["gitstats"]


class Project:
    def __init__(self, name="", path="", vcs=""):
        self.name = name
        self.path = path
        self.vcs = vcs
        self.changes_file = None

    def __str__(self):
        return "Project={0}".format(self.name)

    def __repr__(self):
        return str(self)


def mkproject(path: str):
    if os.path.isdir(path):
        subdirs = os.listdir(path)
        if ".svn" in subdirs:
            vcs = "svn"
        elif ".git" in subdirs:
            vcs = "git"
        else:
            raise FileNotFoundError(f"Project is not a VCS: {path}")
        p = Path(path).absolute()
        project = Project(p.name, path, vcs)
        return project
    else:
        raise FileNotFoundError(f"Project is not a path: {path}")


def walk_projects(source_directory):
    """Scan all main level directories in the projects directory"""
    for project_name in sorted(os.listdir(source_directory)):
        if project_name in project_blacklist:
            continue
        project_path = os.path.join(source_directory, project_name)
        yield mkproject(project_path)


def now():
    return datetime.datetime.now().strftime("%Y-%m-%d %H:%M")


def rest_header(title="", generator=""):
    buffer = StringIO()
    buffer.write(".. note:: Generated by ``{0}`` on {1}".format(generator, now()))
    buffer.write("\n\n")
    buffer.write("=" * len(title) + "\n")
    buffer.write(title + "\n")
    buffer.write("=" * len(title) + "\n")
    buffer.write("\n")
    buffer.seek(0)
    return buffer.read()
