from unittest.mock import patch, MagicMock

from zenyatta.common import get_work_directory, get_docker_metadata, get_sql_metadata
from zenyatta.aws import get_aws_metadata
from zenyatta.aws.s3 import get_base_s3_path
from tests.static.constants import TS_NODASH

MOCKED_WORK_DIR = '/uve/been/mocked'


CONNS = {
    'aws': {'testdb': {'access_key': 'test key',
                       'bucket': 's3://test-bucket',
                       'region': 'us-west-2',
                       'schema': 'testdb',
                       'secret_key': 'secret key'},
            'rds': {'access_key': 'rds test key',
                    'region': 'us-west-2',
                    'secret_key': 'rds secret key'},
            'sns': {'access_key': 'sns access key',
                    'region': 'us-west-2',
                    'secret_key': 'sns secret key',
                    'topic': 'arn:aws:sns:us-west-2:1234:test-topic'}},
    'sql': {
        'test': {'host': 'test.cifgffw7w2ar.us-west-2.rds.amazonaws.com',
                 'password': 'pass',
                 'port': 5432,
                 'schema': 'test',
                 'slots': 3,
                 'conn_type': 'Postgres',
                 'user': 'test'}
    },
    'docker': {
        'aws': {'repository': '641044725657.dkr.ecr.us-west-2.amazonaws.com/d8a/postgres-pitr:latest'}
    }
}


def has_option_true_mock():
    mock = MagicMock()
    mock.has_option = MagicMock(return_value=True)
    mock.get = MagicMock(return_value=MOCKED_WORK_DIR)
    return mock


def has_option_false_mock():
    mock = MagicMock()
    mock.has_option = MagicMock(return_value=False)
    return mock


def test_base_s3_path():
    key = "key"
    conn_id = "conn_id"
    base = get_base_s3_path(key, TS_NODASH, conn_id)
    assert base == key + '/' + TS_NODASH + '/' + conn_id


@patch('zenyatta.common.get_connections', return_value=CONNS)
def test_get_aws_metadata(conns_mock):
    meta = get_aws_metadata('testdb')
    assert meta['access_key'] == 'test key'
    assert meta['bucket'] == 's3://test-bucket'


@patch('zenyatta.common.get_connections', return_value=CONNS)
def test_get_docker_metadata(conns_mock):
    meta = get_docker_metadata('aws')
    assert meta['repository'].startswith('641044725657.dkr.ecr.us-west-2')


@patch('zenyatta.common.get_connections', return_value=CONNS)
def test_get_sql_metadata(conns_mock):
    meta = get_sql_metadata('test')
    assert meta['conn_type'] == 'Postgres'
    assert meta['port'] == 5432
    assert meta['user'] == 'test'


@patch('zenyatta.common.conf', new_callable=has_option_true_mock)
def test_get_work_directory(mock):
    work_dir = get_work_directory()
    assert work_dir == MOCKED_WORK_DIR


@patch('zenyatta.common.conf', new_callable=has_option_false_mock)
def test_default_work_directory(mock):
    work_dir = get_work_directory()
    assert work_dir != MOCKED_WORK_DIR
    assert work_dir == '/mnt'
