#! /usr/bin/env python
#  coding=utf-8

from __future__ import print_function
from os import path, listdir, getcwd
import sys
import click

def err(message):
    click.echo(click.style(message, bold=True, fg="red"))

def succ(message):
    click.echo(click.style(message, bold=True, fg="green"))

def get_candidate_files(path=None):
    path = path or getcwd()
    return [candidate_file for candidate_file in listdir(path) if candidate_file.upper().startswith("CONTRIBUTING")]

def ncoc(*args, **kwargs):
    return """
{title:}

This project adheres to No Code of Conduct.  We are all adults.  We accept everyone's contributions.  Nothing else matters.

For more information please visit the {link} homepage.
""".format(**kwargs)

def determine_style(file):
    for line_number, line in enumerate(open(file, 'r')):
        if line_number==0:
            if line[0] == "#":
                return "md"
        if line_number==1:
            if line[0] in ["-", "=", "*"]:
                return "rst"

def style_ncoc(style="md", level=1):
    if style=="rst":
        levelmarker = ("#" * level) + " "
        title = levelmarker + "Contributor Code of Conduct"
        link =  "[No Code of Conduct](https://github.com/domgetter/NCoC)"
    else:
        levelmarker = "=" if level==1 else "-"
        title = "Contributor Code of Conduct"
        title += ("\n" + (len(title) * levelmarker))
        link = "`No Code of Conduct<https://github.com/domgetter/NCoC>`_"

    return ncoc(title=title, link=link)

def add_coc(filename, append=False, style=None, level=1):
    if append:
        style = determine_style(filename)

    ncoc = style_ncoc(style=style, level=level)

    open_flag = "w" if append is False else "a"
    try:
        with open(path.join(getcwd(), filename), open_flag) as contrib_file:
            print("\n%s" % ncoc, file=contrib_file)
    except Exception as e:
        err(("Writing to %s failed: %s") % (filename, e))
        sys.exit(1)

@click.command()
@click.option('--root', default=getcwd(), help="Project root directory")
@click.option('--add-to-contributing', is_flag=True, help="Append NCoC to CONTRIBUTING or CONTRIBUTING.md (must be in root dir!).")
@click.option('--create-new-file', is_flag=True, help="Create a separate CODEOFCONDUCT file. Define path using --output-filename.")
@click.option('--output-filename', default="CODEOFCONDUCT", help="Output filename and extension")
@click.option('--style', default="md", help="Code of Conduct markup style")
@click.option('--level', default=1, help="Level of heading for code of conduct")
@click.option('--verbose', is_flag=True, help="Enables verbose output")
def add_ncoc(root, add_to_contributing, create_new_file, output_filename, style, level, verbose):
    """
    Appends the NCoC (No Code of Conduct) to your project.
    """

    if add_to_contributing:
        try:
            for each in get_candidate_files():
                style = determine_style(each)
                click.echo("Appending NCoC to {filename:} (style: {style:}).".format(
                    filename=each,
                    style=style
                ))
                add_coc(each, style=style, level=level, append=True)
                succ("NCoC successfully appended to {filename:}".format(filename=output_filename))
                sys.exit(0)
        except Exception as e:
            err(e)
            sys.exit(1)
    elif create_new_file:
        if verbose:
            click.echo("Creating new file {filename:} (style: {style:}).".format(filename=output_filename,
                                                                               style=style))
        try:
            add_coc(filename=output_filename, style=style, level=level, append=False)
            succ("NCoC successfully written to new file {filename:}.".format(filename=output_filename))
        except Exception as e:
            print(e)
            err("Could not write to new file.")
            sys.exit(1)

    sys.exit(0)

if __name__ == '__main__':
     add_ncoc()