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

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


class CCNode(object):
    '''
    Handle node initialization, connection to server, and authentication
    '''
    def __init__(self, server, port, hypervisor, exec_cmd, cert=None):
        '''
        '''
        self.manager = SimpleRpcClient.from_addr(server, port, enable_ssl=True,
                default_handler=handlers.NodeHandler(self, hypervisor,
                                                                    exec_cmd))
        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