import requests
import json
import logging


def authenticate_with_ome(ip_address: str, user_name: str, password: str) -> tuple:
    """
    Authenticates a session against an OME server

    Args:
        ip_address: IP address of the OME server
        user_name: Username for OME
        password: Password for the OME user

    Returns: Returns a tuple of auth_success (bool), headers (dict). Which are true if authentication succeeded
             and {'content-type': 'application/json' respectively.

    """

    """ X-auth session creation """
    auth_success = False
    session_url = "https://%s/api/SessionService/Sessions" % ip_address
    user_details = {'UserName': user_name,
                    'Password': password,
                    'SessionType': 'API'}
    headers = {'content-type': 'application/json'}
    session_info = requests.post(session_url, verify=False,
                                 data=json.dumps(user_details),
                                 headers=headers)
    if session_info.status_code == 201:
        headers['X-Auth-Token'] = session_info.headers['X-Auth-Token']
        auth_success = True
    else:
        error_msg = "Failed create of session with {0} - Status code = {1} - Error: " + str(json.loads(session_info.content))
        logging.error(error_msg.format(ip_address, session_info.status_code))
        exit(0)
    return auth_success, headers