import os
from django.utils.six.moves import configparser as ConfigParser

import pytest

from utilities import EmailsMocking, SMSMocking, HttpRequestsMocking

def pytest_addoption(parser):
    parser.addoption('--without-postgresql-tests', action='store_true',
                     help='disable tests requiring postgresql')


def pytest_runtest_setup(item):
    if 'postgresql' in item.keywords and item.config.option.without_postgresql_tests is True:
        pytest.skip('skipped (PostgreSQL are disabled on command line)')


def site_options(request, pub, section, variable, value):
    config = ConfigParser.ConfigParser()
    path = os.path.join(pub.app_dir, 'site-options.cfg')
    if os.path.exists(path):
        config.read([path])
    if not config.has_section(section):
        config.add_section(section)
    config.set(section, variable, value)
    with open(path, 'w') as site_option:
        config.write(site_option)

    def fin():
        config = ConfigParser.ConfigParser()
        if os.path.exists(path):
            config.read([path])
            config.remove_option(section, variable)
            with open(path, 'w') as site_option:
                config.write(site_option)
    request.addfinalizer(fin)
    return value


@pytest.fixture
def fargo_url(request, pub):
    return site_options(request, pub, 'options', 'fargo_url', 'http://fargo.example.net')


@pytest.fixture
def fargo_secret(request, pub):
    return site_options(request, pub, 'wscall-secrets', 'fargo.example.net', 'xxx')


@pytest.fixture
def welco_url(request, pub):
    return site_options(request, pub, 'options', 'welco_url', 'http://welco.example.net')


@pytest.fixture
def studio(request, pub):
    return site_options(request, pub, 'options', 'studio', 'true')


@pytest.fixture
def emails():
    with EmailsMocking() as mock:
        yield mock


@pytest.fixture
def sms_mocking():
    with SMSMocking() as sms:
        yield sms


@pytest.fixture
def http_requests():
    with HttpRequestsMocking() as http_requests:
        yield http_requests


@pytest.fixture
def nocache(settings):
    settings.CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
        }
    }
