# Path: pyledger/server/handlers.py
# def handle_request(payload: bytes):
#     """
#     Handle a single request
# 
#     :param payload: Serialized PyledgerRequest message
#     :return:
#     """
#     handler = Handler()
#     message = PyledgerRequest()
#     response = PyledgerResponse()
# 
#     try:
#         message.ParseFromString(payload)
#     except DecodeError:
#         response.successful = False
#         response.data = b'Message not properly formatted'
#         return response.SerializeToString()
# 
#     if message.request not in handler_methods(handler):
#         response.successful = False
#         response.data = 'Request type {} not available'.format(message.request).encode()
#         return response.SerializeToString()
# 
#     else:
#         # Handle authentication
#         if message.request in permissions_registry:
#             user = User.from_name(message.user)
#             permission_required = permissions_registry[message.request]
# 
#             if not user.check_password(message.password):
#                 response.successful = False
#                 response.data = b'Wrong user and/or password'
#                 return response.SerializeToString()
# 
#             if user.get_permissions().value > permission_required.value:
#                 response.successful = False
#                 response.data = b'Not enough permissions'
#                 return response.SerializeToString()
# 
#             session = Session.from_key(message.session_key)
# 
#             if not session:
#                 response.successful = False
#                 response.data = b'Session not available'
#                 return response.SerializeToString()
# 
#             if not session.user == user:
#                 response.successful = False
#                 response.data = b'Session not owned by this user'
#                 return response.SerializeToString()
# 
#             if session.until < datetime.datetime.now():
#                 response.successful = False
#                 response.data = b'Session expired, restart your client'
#                 return response.SerializeToString()
# 
#         # Select the function from the handler
#         try:
#             print('Handling message', message)
#             successful, result = getattr(handler, message.request)(message)
#         except Exception as exc:
#             successful = False
#             result = b'Exception in user function: ' + repr(exc).encode('utf-8')
# 
#         response.successful = successful
#         response.data = result
#         return response.SerializeToString()


from pyledger.client.lib import *
from pyledger.server.handlers import handle_request
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.



def test_clientlib_call_request():
    request = call_request(call='add_account', user='master',
                           password='password', contract='AuthDigitalCurrency',
                           data={'key': 'another_account'})

    succesful, response = handle_response(handle_request(request))

    assert succesful == True
    assert response == 'another_account'


def test_clientlib_call_request_fail():
    request = call_request(call='add_account', contract='AuthDigitalCurrency',
                           data={'key': 'yet_another_account'})

    successful, response = handle_response(handle_request(request))

    assert successful == False
    assert response == 'Not enough permissions'


def test_clientlib_call_contracts():
    request = contracts_request()

# Path: pyledger/server/handlers.py
# def handle_request(payload: bytes):
#     """
#     Handle a single request
# 
#     :param payload: Serialized PyledgerRequest message
#     :return:
#     """
#     handler = Handler()
#     message = PyledgerRequest()
#     response = PyledgerResponse()
# 
#     try:
#         message.ParseFromString(payload)
#     except DecodeError:
#         response.successful = False
#         response.data = b'Message not properly formatted'
#         return response.SerializeToString()
# 
#     if message.request not in handler_methods(handler):
#         response.successful = False
#         response.data = 'Request type {} not available'.format(message.request).encode()
#         return response.SerializeToString()
# 
#     else:
#         # Handle authentication
#         if message.request in permissions_registry:
#             user = User.from_name(message.user)
#             permission_required = permissions_registry[message.request]
# 
#             if not user.check_password(message.password):
#                 response.successful = False
#                 response.data = b'Wrong user and/or password'
#                 return response.SerializeToString()
# 
#             if user.get_permissions().value > permission_required.value:
#                 response.successful = False
#                 response.data = b'Not enough permissions'
#                 return response.SerializeToString()
# 
#             session = Session.from_key(message.session_key)
# 
#             if not session:
#                 response.successful = False
#                 response.data = b'Session not available'
#                 return response.SerializeToString()
# 
#             if not session.user == user:
#                 response.successful = False
#                 response.data = b'Session not owned by this user'
#                 return response.SerializeToString()
# 
#             if session.until < datetime.datetime.now():
#                 response.successful = False
#                 response.data = b'Session expired, restart your client'
#                 return response.SerializeToString()
# 
#         # Select the function from the handler
#         try:
#             print('Handling message', message)
#             successful, result = getattr(handler, message.request)(message)
#         except Exception as exc:
#             successful = False
#             result = b'Exception in user function: ' + repr(exc).encode('utf-8')
# 
#         response.successful = successful
#         response.data = result
#         return response.SerializeToString()


# Path: tests/test_8_clientlib.py
from pyledger.client.lib import *
from pyledger.server.handlers import handle_request

#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.



def test_clientlib_call_request():
    request = call_request(call='add_account', user='master',
                           password='password', contract='AuthDigitalCurrency',
                           data={'key': 'another_account'})

    succesful, response = handle_response(handle_request(request))

    assert succesful == True
    assert response == 'another_account'


def test_clientlib_call_request_fail():
    request = call_request(call='add_account', contract='AuthDigitalCurrency',
                           data={'key': 'yet_another_account'})

    successful, response = handle_response(handle_request(request))

    assert successful == False
    assert response == 'Not enough permissions'


def test_clientlib_call_contracts():
    request = contracts_request()

    successful, response = handle_response(handle_request(request))