# -*- 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
from click.testing import CliRunner
import pytest

from .base import VCR
from anaconda_enterprise.cli.main import group
from anaconda_enterprise.cli import config


@pytest.mark.integration
@VCR.use_cassette()
def test_login():
    runner = CliRunner()
    result = runner.invoke(group, ['login'], 'derek\nderek')

    assert result.exception is None
    assert result.output == 'Username: derek\nPassword: \nLogged derek in!\n'
    assert result.exit_code == 0


@pytest.mark.integration
@VCR.use_cassette()
def test_login_failure():
    runner = CliRunner()
    result = runner.invoke(group, ['login'], 'derek\nfail')

    assert result.exit_code == 1


@pytest.mark.integration
@VCR.use_cassette()
def test_login_corrupted_token_store():
    with open(config.config.token_path, 'wb') as fd:
        fd.write(b'f/a/i/l')

    runner = CliRunner()
    result = runner.invoke(group, ['login'], 'derek\nderek')

    assert result.exception is None
    assert result.output == 'Username: derek\nPassword: \nLogged derek in!\n'
    assert result.exit_code == 0


@pytest.mark.integration
@VCR.use_cassette()
def test_logout_successful(tmpdir, monkeypatch):
    _config = config.config
    monkeypatch.setitem(_config.variables, _config.HOME_DIR, tmpdir)

    assert not os.path.exists(config.config.token_path)
    with open(config.config.token_path, 'wb') as fd:
        fd.write(b'secret_token_things')
    assert os.path.exists(config.config.token_path)

    runner = CliRunner()
    result = runner.invoke(group, ['logout'])

    assert result.exception is None
    assert result.exit_code == 0
    assert result.output == "User logged out successfully.\n"
    assert not os.path.exists(config.config.token_path)


@pytest.mark.integration
@VCR.use_cassette()
def test_logout_no_tokenfile(tmpdir, monkeypatch):
    _config = config.config
    monkeypatch.setitem(_config.variables, _config.HOME_DIR, tmpdir)

    assert not os.path.exists(config.config.token_path)

    runner = CliRunner()
    result = runner.invoke(group, ['logout'])

    assert result.output == "User already logged out: no active session found.\n"
    assert not os.path.exists(config.config.token_path)
