import os

from flask import Flask
import pytest
import importlib
import yaml


@pytest.fixture
def temp_config(tmpdir) -> str:
    configfile = str(tmpdir.join('config.yml'))
    vrd_path = tmpdir.mkdir('vrds')
    dir_path = tmpdir.mkdir('pubs')
    apache_config = tmpdir.join('apache.cfg')
    apache_config.write('#start\n')
    flagfile = tmpdir.join('apache_restart')
    platform_path = tmpdir.mkdir('platform')
    ws_module = 'wsap24.so'
    platform_path.join(ws_module).write('\0')

    with open(configfile, 'w') as f:
        yaml.dump({
            'apache_config': str(apache_config),
            'vrd_path': str(vrd_path),
            'dir_path': str(dir_path),
            'url_base': '/1c',
            'platform_path': str(platform_path),
            'ws_module': ws_module,
            'vrd_params': {
                'debug': None,
                'server_addr': 'localhost'
            },
            'infobases': {
                'server_file': 'test/1CV8Clst.lst',
            },
            'apache_restart_flagfile': str(flagfile),
            'url_prefix': 'http://localhost',
        }, f)
    return configfile


@pytest.fixture
def flask_app(temp_config) -> Flask:
    os.environ['WEBPUB1C_CONFIG'] = temp_config
    pub1c = importlib.import_module('pub1c-rest')
    return pub1c.app


@pytest.fixture
def client(flask_app):
    return flask_app.test_client()


def test_index(client):
    response = client.get('/')
    assert b'<!DOCTYPE html>' in response.data


def test_api_index(client):
    response = client.get('/api/v1/')
    data = response.get_json()
    assert data == ['infobases-available', 'infobases-all', 'publications',
                    'module', 'config', 'config-test', 'apache-restart']


def test_api_restart_flag(client):
    endpoint = '/api/v1/apache-restart'
    # test when flag not set
    response = client.get(endpoint)
    assert 404 == response.status_code
    # set flag
    response = client.put(endpoint)
    assert 200 == response.status_code
    # test when flag is set
    response = client.get(endpoint)
    assert 200 == response.status_code


def test_api_config_test(client):
    response = client.get('/api/v1/config-test')
    data = response.get_json()
    assert data == {
            'is_apache_cfg_valid': True,
            'is_vrd_path_valid': True,
            'is_dir_path_valid': True,
            'is_url_base_valid': True,
            'is_module_valid': True,
    }


def test_api_config(client):
    response = client.get('/api/v1/config')
    data = response.get_json()
    expected = ['apache_config', 'apache_restart_flagfile', 'infobases', 'dir_path', 'platform_path',
                'url_base', 'url_prefix', 'vrd_params', 'vrd_path', 'ws_module']
    expected.sort()
    actual = list(data.keys())
    actual.sort()
    assert actual == expected