# -*- coding: utf-8 -*-

import socket

from paramiko import SSHClient, AutoAddPolicy, AuthenticationException

from bssh.utils import env
from bssh.auth import get_pkey
from bssh.logger import logger


def 
(
        hostname=None,
        port=22,
        username=None,
        password=None,
        pkey=None,
        pkey_pwd=None,
        sock=None,
        timeout=env.timeout,
        **kwargs
):
    """Connect the remote ssh server"""
    passauth = True if password else False
    pkey = pkey if passauth else get_pkey(pkey, pkey_pwd)

    client = SSHClient()
    client.set_missing_host_key_policy(AutoAddPolicy())
    try:
        client.connect(hostname=hostname,
                       port=int(port),
                       username=username,
                       password=password,
                       pkey=pkey,
                       sock=sock,
                       timeout=timeout)
        logger.login.debug('%s connect successfully.' % hostname)
        return client
    except AuthenticationException:
        logger.login.error('%s Validation failed.' % hostname)
    except socket.error:
        logger.login.error('%s Network Error' % hostname)
    except Exception as e:
        logger.login.error('%s %s' % (hostname, str(e)))

connect