#  BSD 3-Clause License
#
#  Copyright (c) 2019, Elasticsearch BV
#  All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are met:
#
#  * Redistributions of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer.
#
#  * Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
#  * Neither the name of the copyright holder nor the names of its
#    contributors may be used to endorse or promote products derived from
#    this software without specific prior written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
#  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
#  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
#  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
#  SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
#  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import os

import pytest

from elasticapm.conf.constants import TRANSACTION

pyodbc = pytest.importorskip("pyodbc")

pytestmark = [pytest.mark.pyodbc]


if "POSTGRES_DB" not in os.environ:
    pytestmark.append(pytest.mark.skip("Skipping pyodbc tests, no POSTGRES_DB environment variable set"))


@pytest.fixture(scope="function")
def pyodbc_postgres_connection(request):
    conn_str = ("DRIVER={PostgreSQL Unicode};" "DATABASE=%s;" "UID=%s;" "PASSWORD=%s;" "SERVER=%s;" "PORT=%s;") % (
        os.environ.get("POSTGRES_DB", "elasticapm_test"),
        os.environ.get("POSTGRES_USER", "postgres"),
        os.environ.get("POSTGRES_PASSWORD", "postgres"),
        os.environ.get("POSTGRES_HOST", None),
        os.environ.get("POSTGRES_PORT", "5432"),
    )
    conn = pyodbc.connect(conn_str)
    cursor = conn.cursor()
    cursor.execute(
        "CREATE TABLE test(id int, name VARCHAR(5) NOT NULL);"
        "INSERT INTO test VALUES (1, 'one'), (2, 'two'), (3, 'three');"
    )

    yield conn

    # cleanup
    cursor.execute("ROLLBACK")


@pytest.mark.integrationtest
def test_pyodbc_select(instrument, pyodbc_postgres_connection, elasticapm_client):
    cursor = pyodbc_postgres_connection.cursor()
    query = "SELECT * FROM test WHERE name LIKE 't%'"

    try:
        elasticapm_client.begin_transaction("web.django")
        cursor.execute(query)
        cursor.fetchall()
        elasticapm_client.end_transaction(None, "test-transaction")
    finally:
        transactions = elasticapm_client.events[TRANSACTION]
        spans = elasticapm_client.spans_for_transaction(transactions[0])
        span = spans[0]
        assert span["name"] == "SELECT FROM test"
        assert span["type"] == "db"
        assert span["subtype"] == "pyodbc"
        assert span["action"] == "query"
        assert "db" in span["context"]
        assert span["context"]["db"]["instance"] == "elasticapm_test"
        assert span["context"]["db"]["type"] == "sql"
        assert span["context"]["db"]["statement"] == query
        assert span["context"]["service"]["target"]["type"] == "pyodbc"
        assert span["context"]["service"]["target"]["name"] == "elasticapm_test"


@pytest.mark.integrationtest
def test_psycopg2_rows_affected(instrument, pyodbc_postgres_connection, elasticapm_client):
    cursor = pyodbc_postgres_connection.cursor()
    try:
        elasticapm_client.begin_transaction("web.django")
        cursor.execute("INSERT INTO test VALUES (4, 'four')")
        cursor.execute("SELECT * FROM test")
        cursor.execute("UPDATE test SET name = 'five' WHERE  id = 4")
        cursor.execute("DELETE FROM test WHERE  id = 4")
        elasticapm_client.end_transaction(None, "test-transaction")
    finally:
        transactions = elasticapm_client.events[TRANSACTION]
        spans = elasticapm_client.spans_for_transaction(transactions[0])

        assert spans[0]["name"] == "INSERT INTO test"
        assert spans[0]["context"]["db"]["rows_affected"] == 1

        assert spans[1]["name"] == "SELECT FROM test"
        assert "rows_affected" not in spans[1]["context"]["db"]

        assert spans[2]["name"] == "UPDATE test"
        assert spans[2]["context"]["db"]["rows_affected"] == 1

        assert spans[3]["name"] == "DELETE FROM test"
        assert spans[3]["context"]["db"]["rows_affected"] == 1
