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

from click.testing import CliRunner
import pytest

from .base import VCR, FIXTURES
from anaconda_enterprise.cli.main import group

pkg_dir = os.path.join(FIXTURES, "conda-mirror", "linux-64")


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

    result = runner.invoke(group, ['channels', 'create', 'test1'])

    result = runner.invoke(group, [
        'upload', '--channel', 'test1', os.path.join(pkg_dir, "affine-2.0.0-py27_0.tar.bz2"),
        os.path.join(pkg_dir, "affine-2.0.0-py34_0.tar.bz2")
    ])

    assert result.exit_code == 0

    result = runner.invoke(
        group,
        ['packages', 'list-files', 'test1', 'affine'], )

    assert len(re.findall('affine-2.0.0', result.output)) == 2
    assert result.exit_code == 0

    result = runner.invoke(
        group,
        [
            'packages', 'delete', 'test1', 'affine', '--file',
            'linux-64/affine-2.0.0-py27_0.tar.bz2'
        ],
        input='Y\n', )
    assert result.exit_code == 0

    result = runner.invoke(
        group,
        ['packages', 'list-files', 'test1', 'affine'], )

    assert len(re.findall('affine-2.0.0', result.output)) == 1
    assert len(re.findall('affine-2.0.0-py34_0.tar.bz2', result.output)) == 1
    assert result.exit_code == 0


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

    result = runner.invoke(group, ['channels', 'create', 'test1'])

    result = runner.invoke(
        group,
        ['upload', '--channel', 'test1', os.path.join(pkg_dir, "alabaster-0.7.7-py27_0.tar.bz2")])

    assert result.exit_code == 0

    result = runner.invoke(
        group,
        ['packages', 'list-files', 'test1', 'alabaster'], )

    assert 'alabaster-0.7.7-py27_0.tar.bz2' in result.output
    assert result.exit_code == 0

    result = runner.invoke(
        group,
        [
            'packages', 'delete', 'test1', 'alabaster', '--file',
            'linux-ppc64le/alabaster-0.7.7-py27_0.tar.bz2'
        ],
        input='Y\n', )
    assert result.exit_code == 0

    result = runner.invoke(
        group,
        ['packages', 'list-files', 'test1', 'alabaster'], )

    assert 'Error: Package "test1/alabaster" was not found\n' == result.output
    assert result.exit_code == 1
