#!/usr/bin/python


from manage import Manager
from storm import Storm
from storm.exceptions import StormValueError

from termcolor import colored

manager = Manager()
storm_ = Storm()


def get_formatted_message(message, format_type):

    def fixed_width(text, size):
        text_width = len(text)
        if size > text_width:
            for i in range(text_width, size):
                text = text + " "

        return text

    format_typed = fixed_width(format_type, 8)
    all_message = ""
    message = " %s" % message

    if format_type == 'error':
        all_message = colored(format_typed, 'white', 'on_red')
    if format_type == 'success':
        all_message = colored(format_typed, 'white', 'on_green')

    return all_message+message


@manager.command
def add(name, host, user, port=22, id_file=""):
    """
    Adds a new entry to sshconfig.
    """
    try:
        result = storm_.add_entry(name, host, user, port, id_file)
        return get_formatted_message('{0} added to your ssh config. you can connect it by typing "ssh {0}".'.format(
            name
        ), 'success')
    except StormValueError as error:
        return get_formatted_message(error, 'error')


@manager.command
def edit(name, host, user, port=22, id_file=""):
    """
    Edits the related entry already defined in ssh config.
    """
    try:
        result = storm_.edit_entry(name, host, user, port, id_file)
        return get_formatted_message(
            '"{0}" updated successfully.'.format(
                name
            ), 'success')
    except StormValueError as error:
        return get_formatted_message(error, 'error')

@manager.command
def delete(name):
    """
    Deletes a single host.
    """
    try:
        result = storm_.delete_entry(name)
        return get_formatted_message('hostname "{0}" deleted successfully.'.format(name), 'success')
    except StormValueError as error:
        return get_formatted_message(error, 'error')

@manager.command
def list():
    """
    Lists all hosts from ssh config.
    """
    try:
        result = 'listing entries:\n'
        for host in storm_.list_entries(order=True):

            if ' ' in host.get("options").get("hostname"):
                host["options"]["hostname"] = host["options"]["hostname"].replace(" ", "|")

            result += "  {0} -> {1}@{2}:{3}\n".format(
                host["host"],
                host.get("options").get("user"),
                host.get("options").get("hostname"),
                host.get("options").get("port")
            )

        return result
    except Exception as error:
        return get_formatted_message(str(error), 'error')

@manager.command
def delete_all():
    """
    Deletes all hosts from ssh config.
    """
    try:
        storm_.delete_all_entries()
        return get_formatted_message('all entries deleted.', 'success')
    except Exception as error:
        return get_formatted_message(str(error), 'error')


manager.main()



