import json
import socket
import sys

import click
from ..client import Client
from ..errors.common import AuthenticationError, InvalidConfig
from tabulate import tabulate


def client(system='default', config=None, config_path=None, catch_exceptions=True):
    if not catch_exceptions:
        return Client(system, config, config_path)

    try:
        netlab_client = Client(system, config, config_path)
    except InvalidConfig as e:
        click.secho("{}: {}".format(type(e).__name__, e), fg='red')
        click.secho("Check your config.json file for errors.")
        sys.exit(1)
    except json.JSONDecodeError as e:
        click.secho("{}: {}".format(type(e).__name__, e), fg='red')
        click.secho("Your config.json file has syntax errors and cannot be decoded.")
        sys.exit(1)
    except AuthenticationError as e:
        click.secho("{}: {}".format(type(e).__name__, e), fg='red')
        click.secho("Check your API key for problems. Make sure you are using the correct user, token, and source "
                    "IP address. Make sure your API key is active.")
        sys.exit(1)
    except socket.error as e:
        click.secho("{}: {}".format(type(e).__name__, e), fg='red')
        click.secho("Problem connecting to the Remote API socket. Check that the Remote API is enabled. "
                    "Wait one minute and try again. Also ensure the host setting is correct.")
        sys.exit(1)
    else:
        return netlab_client


def output(data, tablefmt='pipe', headers=(), **kwargs):
    """ Helper function to output data in tables. Accepts tabulate and click.secho options. """
    try:
        click.secho(tabulate(data.items(), tablefmt=tablefmt, headers=headers), **kwargs)
    except AttributeError:
        click.secho(tabulate(data, tablefmt=tablefmt, headers=headers), **kwargs)
