import socket
import threading
import ssl
import logging
from sjrpc.client import SimpleRpcClient
from sjrpc.utils import ConnectionProxy
from sjrpc.core import RpcError
from ccnodehandlers import *


class CCNode(object):
    '''
    This class handles node initialization and connection and authentication
    '''
    def __init__(self, server, port, hypervisor, cert=None):
        self.manager = SimpleRpcClient.from_addr(server, port, enable_ssl=True,
                                default_handler=NodeHandler(self, hypervisor))
        self.server = ConnectionProxy(self.manager)

    def run(self):
        self.manager.run()

    def authentify(self, login, password):
        logging.debug('Authenticating user %s with password <%s>' % (login,
                      password))
        try:
            role = self.server.authentify(login, password)
        except RpcError as err:
            if err.exception == 'AuthenticationError':
                logging.warning('Authentication error')
            else:
                logging.warning('Unknown error while authenticating: %s' % err)
            return False
        else:
            if role != 'hypervisor':
                logging.warning('Bad role affected by server: %s' % role)
                return False
            else:
                return True