
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

import json
import pytest
import requests
import random
import os
#from pytest_cases import fixture_plus

def get_params_from_file(param,api_name=None):
    with open(os.path.join(os.path.dirname(os.path.abspath(__file__)),"params_captured.json")) as fobj:
        params = json.load(fobj)
    if os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)),"input_params.json")):
        with open(os.path.join(os.path.dirname(os.path.abspath(__file__)),"input_params.json")) as fobj:
            input_params = json.load(fobj)
        params.update(input_params)

    generic_values = []
    if param in params:
        if type(params[param]) is list:
            generic_values = random.choice(params[param])
        else:
            generic_values = params[param]
    #try:
    for api, params_info in params.items():
        if type(params_info) is not dict:
            continue
        if api_name:
            if api not in str(api_name).lower():
                continue
        if param in params_info:
            values = params[api][param]
            if values:
                if type(values) is list:
                    if None in values:
                        values.remove(None)
                    return random.choice(values)
                else:
                    return values
            else:
                return None
    # except:
    #     pass
    if generic_values:
        return generic_values
    else:
        return None

def pytest_addoption(parser):
    #parser.addoption("--host", action="store", default="")
    parser.addoption("--url_prefix", action="store", default="")
    {% for input in AUTH_INPUTS %}
    parser.addoption("--{{ input }}", action="store", default="")
    {% endfor %}

#@pytest.fixture(scope="session", autouse=True)
#def host(pytestconfig):
#    return pytestconfig.getoption("host")

@pytest.fixture(scope="session", autouse=True)
def url_prefix(pytestconfig):
    return pytestconfig.getoption("url_prefix")

{% for input in AUTH_INPUTS %}
@pytest.fixture(scope="session", autouse=True)
def {{ input }}(pytestconfig):
    return pytestconfig.getoption("{{ input }}")
{% endfor %}

{% if AUTH_API %}
@pytest.fixture(scope="module", autouse=True)
def access_token({{ AUTH_INPUTS | join(", ") }}):
    resp = requests.post(host+"{{ AUTH_API }}",
                    headers={ {% for k, v in AUTH_API_HEADERS.items() %}{% if v in AUTH_INPUTS %}'{{ k }}':{{ v }}{% else %}'{{ k }}':'{{ v }}'{% endif %},{% endfor %} },
                    data=json.dumps({{ AUTH_API_PAYLOAD }}))
    if resp.status_code == 200:
        os.environ["CVDAST_ACCESS_TOKEN"] = resp.json()["{{ AUTH_RESP_KEY }}"]
        return resp.json()["{{ AUTH_RESP_KEY }}"]
    else:
        print("AUTHENTICATION is not successful, please check the creds!")
        raise SystemExit
{% endif %}

@pytest.fixture(scope="session", autouse=True)
def update_headers(request):
    def _mask(*args, **kwargs):
        headers = kwargs["headers"]
        for k, v in headers.items():
            res = get_params_from_file(k,kwargs.get("api"))
            if res:
                headers[k] = res
        return headers
    return _mask

{% set params_covered = [] %}{% for api,params in api_info.items() %}{% for param,values in params.items() %}{% if param not in params_covered %}
@pytest.fixture(scope="session", autouse=True)
#@fixture_plus(params=get_params_from_file("{{ param }}"))
def {{ param }}({% if param in nested_params %}{{ nested_params[param] | unique | join(", ")}}{% else %}request{% endif %}):
    #return request.param
    {% if param in api_detailed_info %}
    return {{ api_detailed_info[param] | replace("'$","") | replace("$'","") }}
    {% else %}
    return get_params_from_file("{{ param }}")
    {% endif %}
{% set params_covered = params_covered.append(param) %}
{% endif %}{% endfor %}{% endfor %}

{% set params_nested = [] %}
{% for param in more_params %}
@pytest.fixture(scope="session", autouse=True)
def {{ param }}(request):
    return get_params_from_file("{{ param }}")
{% endfor %}