#!/Users/Daniel/.pyenv/versions/3.6.3/bin/python
"""
Usage: gci-validator (FILE)

--version               Show program version

"""
from docopt import docopt
import csv
import os
import sys


REQUIRED_FIELDS = ["name", "description", "mentors",
                   "categories", "time_to_complete_in_days"]
VALID_FIELDS = {
    "name": lambda x: len(x) <= 200,
    "description": lambda x: len(x) <= 500,
    "status": lambda x: x == "1" or x == "2",
    "max_instances": lambda x: int(x) > 0 and int(x) <= 100,
    "mentors": lambda x: len(x.split(",")) <= 30,
    "is_beginner": lambda x: True,
    "tags": lambda x: True,
    "categories": lambda x: len([item for item in x.split(',') if item not in ['1', '2', '3', '4', '5']]) == 0,
    "time_to_complete_in_days": lambda x: int(x) >= 3 and int(x) <= 7,
    "private_metadata": lambda x: len(str(x)) <= 80,
    "external_url": lambda x: True
}


def not_valid_categories(input):
    return not str(input) in ["1", "2", "3", "4", "5"]


def get_missing_fields(fields):
    return list(set(REQUIRED_FIELDS) - set(fields) & set(REQUIRED_FIELDS))


def validate_row(index, row):
    for field, value in row.items():
        if not value:
            if field in REQUIRED_FIELDS:
                print("{0} - Required field left blank: {1}".format(index, field))
            continue
        elif not VALID_FIELDS[field](value):
            print("{0} - Invalid field '{1}':{2}".format(
                index, field, value)
            )


if __name__ == '__main__':
    arguments = docopt(__doc__, version="0.0.1")
    file_name = arguments["FILE"]
    if os.path.exists(file_name):
        with open(file_name, mode="r") as file:
            try:
                reader = csv.DictReader(file, )
                missing_fields = get_missing_fields(reader.fieldnames)
                if len(missing_fields) > 0:
                    print("The following fields are required: {0}".format(
                        missing_fields)
                    )
                    sys.exit(0)
                for index, row in enumerate(reader):
                    validate_row(index+1, row)
                print("Finished")
            except TypeError as err:
                print(err)
    else:
        print("File '{0}' not found".format(file_name))
