from willie.module import commands
import itertools # itertools is used for the username combination possibility

#>>> import itertools
#>>> map(''.join, itertools.product(*((c.upper(), c.lower()) for c in 'Fox')))
#['FOX', 'FOx', 'FoX', 'Fox', 'fOX', 'fOx', 'foX', 'fox']

class FileIO:

    def __init__(self, username):
        self.storage = "Upboats.txt"
        self.finished_upboats = None
        self.username = username

    def finished(self):
        # check how many upboats
        return self.finished_upboats

    def upboat(self):
        line_number = -1

        # variable will become a list of possible username combinations
        username_combination_list = map(''.join, itertools.product(*((c.upper(), c.lower()) for c in self.username)))

        found = False

        # Read every line in the text file and check if the input name is in there
        for item in self.storage.split("\n"):
            if found is True:
                break
            line_number += 1
            for name in username_combination_list:
                if name in item:
                    unprocessed = item.split(",") # This only works if the line is a "name,upboatnumber" otherwise it will probably throw mad exceptions
                    # Output : ["name", "2"]
                    found = True
                    self.finished_upboats = (int(unprocessed[1]) + 1)

        # Try checking if the name was found, if it's not found (aka nameerror) it will add a new line
        try:
            unprocessed
        except NameError: # Name wasn't found, add it to the file
            storage = open(self.storage, "a").readlines() # a is append, open the file and put the file pointer at the end
            storage.write("%s,1\n" % self.username)
            storage.close()
            self.finished_upboats = 1
        else:
            newtext = open(self.storage, "r").readlines() # r+ is read&write
            replacement = str("%s,%s\n" % (self.username, ((int(unprocessed[1])+1))))
            newtext[line_number] = replacement
            storage = open(self.storage, "w")
            storage.writelines(newtext)
            storage.close()

@commands('up', 'upboat', 'upvote')

def up(bot, trigger):

    if trigger.group(2) == trigger.nick:
        return bot.say("Can't upboat yourself, dork!")

    elif not trigger.group(2): # Nothing is entered after .upboat
        return bot.say("You have to enter a name to upboat, aho!")

    elif trigger.group(2) is not "":
        try:
            user = FileIO(username=trigger.group(2))
            user.upboat()
            upboats = user.finished()
            # remove instance to prevent ram overflowing
            del user
            if upboats == 1:
                return bot.say("User %s added! %s now has 1 upboat!" % (trigger.group(2),trigger.group(2)))
            else:
                return bot.say("%s Upboats: %s" % (trigger.group(2), upboats))
        except Exception as e:
            return bot.say("Something went wrong. See bakaboykie for shit coding. Exception: %s" % e)

    else: # Wrong name is entered, will display a warning message.
        return bot.say("Something went wrong. See bakaboykie for shit coding.")