# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2016 Continuum Analytics, Inc.
#
# May be copied and distributed freely only as part of an Anaconda or
# Miniconda installation.
# -----------------------------------------------------------------------------
import os
import pytest

from anaconda_enterprise.cli.config import ConfigManager, platform_defaults, SCHEMA_LATEST

paths = platform_defaults + ('{root}/{component_file}', )
CA_CHAIN = os.environ.get('CA_CHAIN', os.path.join('..', 'build', 'certs', 'rootca.crt'))


class TestConfigManager(ConfigManager):
    def __init__(self, component, version, path):
        super(TestConfigManager, self).__init__(component, version)
        self.variables['root'] = path

    @property
    def user_local_save_path(self):
        return "{root}/{component_file}".format(**self.variables)

    def get_search_path(self):
        return [path.format(**self.variables) for path in paths]

    @property
    def token_path(self):
        return '{root}/tokens.json'.format(**self.variables)


@pytest.fixture()
def config_manager(monkeypatch, tmpdir):
    root = tmpdir.mkdir('cli-root-cm')

    root.join('cli.yml').write('''
version: '{version}'
default_site: example
sites:
  example:
    url: "https://repo.anaconda.example.com:8089/api"
    ssl_verify: {ca_chain}
'''.format(
        version=SCHEMA_LATEST, ca_chain=CA_CHAIN))
    mgr = TestConfigManager('cli', SCHEMA_LATEST, str(root))
    mgr.load_schema()
    mgr.load_files()
    monkeypatch.setattr('anaconda_enterprise.cli.config.config', mgr)
    return mgr


@pytest.fixture(autouse=True)
def config(monkeypatch, tmpdir):
    root = tmpdir.mkdir('cli-root')

    root.join('cli.yml').write('''
version: '{version}'
default_site: example
sites:
  example:
    url: "https://anaconda.example.com/repository/api"
    ssl_verify: {ca_chain}
'''.format(
        version=SCHEMA_LATEST, ca_chain=CA_CHAIN))

    mgr = TestConfigManager('cli', SCHEMA_LATEST, str(root))
    monkeypatch.setattr('anaconda_enterprise.cli.config.config', mgr)
    return root


@pytest.fixture()
def config_v0(monkeypatch, tmpdir):
    root = tmpdir.mkdir('cli0-root')

    root.join('cli.yml').write('''
default_site: example
sites:
  example:
    url: "https://anaconda.example.com/repository/api"
    verify_ssl: {ca_chain}
'''.format(ca_chain=CA_CHAIN))

    mgr = TestConfigManager('cli', SCHEMA_LATEST, str(root))
    monkeypatch.setattr('anaconda_enterprise.cli.config.config', mgr)
    return root
