'''
Equal Parts utilities module

Utility functions, mostly dealing with user input/output and
file-system stuff.
'''
import sys
import os
import re
import io
import datetime
import yaml

# Parse an input string
def processInput(string):
    inTerm = False
    inQuotes = False
    terms = []
    term = io.StringIO()
    for c in string:
        
        if re.match(r"\s", c):
            if inQuotes:
                term.write(c)
            else:
                if term.getvalue():
                    terms.append(term.getvalue())
                    term = io.StringIO()
        elif c == "\"":
            if inQuotes:
                if term.getvalue():
                    terms.append(term.getvalue())
                    term = io.StringIO()
                inQuotes = False
            else:
                inQuotes = True
        else:
            term.write(c)
    
    if term.getvalue():
        terms.append(term.getvalue())
    
    return terms

# Show a formatted error message and optionally exit
def error(message):
    print("[epsm] Error:", message)

# Show a formatted information message - if ver is true, only print if the verbose env variable is set
def info(message, ver=False):
    if not ver or (ver and "EPSM_VERBOSE" in os.environ):
        print("[epsm]", message)

# Recursively cd up until either .epconfig is found or we reach /
def getWebsiteRoot():
    path = str(os.getcwd())
    osRoot = os.path.abspath(os.sep)
    while path != osRoot:
        if os.path.isfile("epconfig.yml") and not os.path.islink("epconfig.yml"):
            return path
        else:
            os.chdir("..")
            path = str(os.getcwd())
    error("this is not a valid website")
    sys.exit(1)

# Asks a y/n question, returns true if y, false if n
def askYN(question):
    answer = input(question + " (Y/n) ").lower()
    if answer == "" or answer == "y" or answer == "yes":
        return True
    else:
        return False

# Ensure that a directory exists, return false if it does not
def ensureDir(absolutePath):
    if os.path.exists(absolutePath):
        return True
    else:
        if askYN("Directory " + absolutePath + " has not been found, would you like to create it?"):
            try:
                os.mkdir(absolutePath)
                return True
            except:
                return False
        else:
            return False

# Add the date prefix in proper slugified format
def addDatePrefix(string):
    return datetime.date.isoformat(datetime.date.today()) + "-" + string

# Condition strings for URLs
def slugify(string, addDate=False):
    slug = string.lower()
    slug = re.sub("[^a-z0-9]+", "-", slug).strip("-")
    if addDate:
        slug = addDatePrefix(slug)
    return slug

# Do directory stuff
def listFiles(directory):
    if os.path.isdir(directory):
        fileList = []
        for index, filename in enumerate(os.listdir(directory)):
            fileList.append([directory, filename])
            print("\t", index, ":", filename)
        print("\t q : quit")
    
        rawInput = input("Choose one or more files: ").strip()
        # check that input consists of integers and spaces only
        if rawInput and re.search("[^0-9 ]", rawInput) == None:
            selectedFiles = set(re.split(" +", rawInput))
            for selection in selectedFiles:
                index = int(selection)
                if index < len(fileList):
                    yield fileList[index]
                else:
                    info(selection + " does not correspond to a file, skipping...")
        elif rawInput == "q":
            return
        else:
            raise Exception(rawInput + " is not a valid input")  
    else:
        raise Exception(directory + " is invalid")
    
