# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
# Copyright (C) NIWA & British Crown (Met Office) & Contributors.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import asyncio
import logging
from pathlib import Path
from random import random

import pytest

from cylc.flow.async_util import (
    pipe,
    asyncqgen,
    scandir,
)

LOG = logging.getLogger('test')


@pipe()
async def a_range(n):
    for num in range(n):
        LOG.info(f'a_range({n})')
        yield num


@pipe
async def even(x):
    LOG.info(f'even({x})')
    return x % 2 == 0


@pipe
async def mult(x, y, kwarg='useless kwarg'):
    LOG.info(f'mult{x, y}')
    return x * y


@pipe
async def sleepy(x):
    """A filter which waits a while then passes."""
    LOG.info(f'sleepy({x})')
    await asyncio.sleep(0.1)
    return True


@pytest.mark.parametrize('preserve_order', (True, False))
async def test_pipe(preserve_order):
    """It passes values through the pipe."""
    pipe = a_range(5) | even | mult(2)
    pipe.preserve_order = preserve_order

    result = []
    async for num in pipe:
        result.append(num)

    assert result == [
        0,
        4,
        8,
    ]


@pytest.mark.parametrize('preserve_order', (True, False))
async def test_pipe_single(preserve_order):
    """It allow single-step pipes."""
    pipe = a_range(5)
    pipe.preserve_order = preserve_order

    result = []
    async for num in pipe:
        result.append(num)

    assert result == [
        0,
        1,
        2,
        3,
        4
    ]


@pytest.mark.parametrize('preserve_order', (True, False))
async def METHOD_NAME(preserve_order):
    """It can be re-used once depleted."""
    pipe = a_range(5) | even | mult(2)
    pipe.preserve_order = preserve_order

    for _ in range(5):
        result = []
        async for num in pipe:
            result.append(num)

        assert result == [
            0,
            4,
            8,
        ]


@pytest.mark.parametrize('preserve_order', (True, False))
async def test_pipe_filter_stop(preserve_order):
    """It yields values early with the filter_stop argument."""
    pipe = a_range(5) | even(filter_stop=False)
    pipe |= mult(10)
    pipe.preserve_order = preserve_order

    result = []
    async for num in pipe:
        result.append(num)

    # the even numbers should be multiplied by 10
    # the odd numbers should be yielded early (so don't get multiplied)
    assert result == [
        0,
        1,
        20,
        3,
        40,
    ]


@pipe
async def one(x):
    await asyncio.sleep(random() / 5)
    return x


@pytest.mark.parametrize('preserve_order', (True, False))
async def test_pipe_preserve_order(preserve_order):
    """It should control result order according to pipe configuration."""
    n = 50
    pipe = a_range(n) | one | one | one
    pipe.preserve_order = preserve_order

    result = []
    async for item in pipe:
        result.append(item)

    # the odds of getting 50 items in order by chance are pretty slim
    assert (result == list(range(n))) is preserve_order


@pytest.mark.parametrize('preserve_order', (True, False))
async def test_pipe_concurrent(caplog, preserve_order):
    """It runs pipes concurrently.

    It is easy to make something which appears to be concurrent, this
    test is intended to ensure that it actually IS concurrent.

    """
    pipe = a_range(5) | even | sleepy | mult(2)
    pipe.preserve_order = preserve_order

    caplog.set_level(logging.INFO, 'test')
    async for num in pipe:
        pass

    order = [
        # a list of the log messages generated by each step of the pipe
        # as it processes an item
        x[2].split('(')[0]
        for x in caplog.record_tuples
    ]

    assert 'mult' in order
    assert len(order) == 4 * 4  # 4 steps * 4 items yielded by a_range

    # ensure that the steps aren't completed in order (as sync code would)
    # the sleep should ensure this
    # NOTE: not the best test but better than nothing
    assert order != [
        'a_range',
        'even',
        'sleepy',
        'mult'
    ] * 4


def test_pipe_str():
    """It has helpful textual representations."""
    pipe = a_range(5) | even(filter_stop=False) | mult(10, kwarg=42)
    assert str(pipe) == 'a_range(5)'
    assert repr(pipe) == 'a_range(5) | even() | mult(10, kwarg=42)'


@pipe()  # NOTE: these brackets are what the next function is testing
async def div(x, y):
    return x / y


def test_pipe_brackets():
    """Ensure that pipe functions can be declared with or without brackets."""
    pipe = a_range(5) | div
    assert repr(pipe) == 'a_range(5) | div()'


@pipe
async def documented(x):
    """The docstring for the pipe function."""
    pass


def test_documentation():
    """It should preserve the docstring of pipe functions."""
    assert documented.__doc__ == 'The docstring for the pipe function.'


def test_rewind():
    """It should be possible to move throught the pipe stages."""
    pipe = a_range | mult | even
    assert pipe.fastforward().rewind() == pipe


async def test_asyncqgen():
    """It should provide an async gen interface to an async queue."""
    queue = asyncio.Queue()

    gen = asyncqgen(queue)

    await queue.put(1)
    await queue.put(2)
    await queue.put(3)

    ret = []
    async for item in gen:
        ret.append(item)

    assert ret == [1, 2, 3]


async def test_scandir(tmp_path: Path):
    """It should list directory contents (including symlinks)."""
    (tmp_path / 'a').touch()
    (tmp_path / 'b').touch()
    (tmp_path / 'c').symlink_to(tmp_path / 'b')

    assert sorted(await scandir(tmp_path)) == [
        Path(tmp_path, 'a'),
        Path(tmp_path, 'b'),
        Path(tmp_path, 'c')
    ]


async def test_scandir_non_exist(tmp_path: Path):
    """scandir() should raise FileNotFoundError if called on a path that
    doesn't exist."""
    with pytest.raises(FileNotFoundError):
        await scandir(tmp_path / 'HORSE')