from uuid import uuid4

import main
from yaml import dump


class TokenCommand:
    def __init__(self, *args):
        self.token(*args)

    def token(
        self, addr, authed, data, obj, spl, success, failure, info, incUsage, length
    ):
        if authed:
            if length == 2:
                if spl[1] == "list":
                    info(dump(main.tokens))
                    return
                else:
                    incUsage("token")
                    return
            elif length == 3:
                if spl[1] == "del":
                    if spl[2] in main.tokens.keys():
                        del main.tokens[spl[2]]
                        main.saveConf("tokens")
                        success("Successfully removed token: %s" % spl[2])
                        return
                    else:
                        failure("No such token")
                        return
                else:
                    incUsage("token")
                    return
            elif length == 4:
                if spl[1] == "add":
                    if not spl[2] in main.tokens.keys():
                        if spl[3] in ["relay", "api"]:  # more to come!
                            main.tokens[spl[2]] = {
                                "hello": str(uuid4()),
                                "usage": spl[3],
                                "counter": str(uuid4()),
                            }
                            main.saveConf("tokens")
                            success("Successfully created token %s:" % spl[2])
                            info(dump(main.tokens[spl[2]]))
                            return
                        else:
                            incUsage("token")
                            return
                    else:
                        failure("Token already exists: %s" % spl[2])
                        return
                else:
                    incUsage("token")
                    return
            else:
                incUsage("token")
                return
        else:
            incUsage(None)
