import pytest

from credmgr.exceptions import Conflict, NotFound, ServerError
from credmgr.models import DatabaseCredential

data = {
    "name": "test_database_credential",
    "database_username": "database_username",
    "database_host": "database_host",
    "database": "database",
    "database_flavor": "database_flavor",
    "database_port": "6543",
    "database_password": "database_password",
    "use_ssh": True,
    "ssh_host": "ssh_host",
    "ssh_port": "1234",
    "ssh_username": "ssh_username",
    "ssh_password": "ssh_password",
    "use_ssh_key": True,
    "private_key": "private_key",
    "private_key_passphrase": "private_key_passphrase",
}


def test_create_database_credential(recorder, credential_manager):
    database_credential = credential_manager.database_credential.create(**data)
    print(database_credential.id)
    for key, value in data.items():
        assert getattr(database_credential, key) == value


def test_create_database_credential_other_user(recorder, credential_manager):
    new_data = {**data, "owner": 4}
    database_credential = credential_manager.database_credential.create(
        **{**new_data, "owner": 4}
    )
    for key, value in new_data.items():
        if key == "owner":
            assert getattr(database_credential, key).id == value
            continue
        assert getattr(database_credential, key) == value


def test_create_database_credential_bad_params(recorder, credential_manager):
    data = {"name": "se"}
    with pytest.raises(ServerError):
        _ = credential_manager.database_credential.create(**data)


def test_create_database_credential_existing(recorder, credential_manager):
    with pytest.raises(Conflict):
        _ = credential_manager.database_credential.create(**data)


def test_delete_database_credential(recorder, credential_manager):
    database_credential = credential_manager.database_credential(3)
    database_credential.delete()
    with pytest.raises(NotFound):
        _ = credential_manager.database_credential(3)


def test_edit_database_credential(recorder, credential_manager):
    database_credential = credential_manager.database_credential(3)
    database_credential.edit(database_username="new_username")
    assert database_credential.database_username == "new_username"


def test_edit_database_credential_conflicting_data(recorder, credential_manager):
    database_credential = credential_manager.database_credential(4)
    with pytest.raises(Conflict):
        database_credential.edit(name="test_database_credential")


def test_list_database_credentials(recorder, credential_manager):
    database_credentials = credential_manager.database_credentials()
    for database_credential in database_credentials:
        assert isinstance(database_credential, DatabaseCredential)
