import os
import re
import shutil
import subprocess
import tempfile
from typing import List

import pytest
from click.testing import CliRunner

import renkubio.cli as rbc


def parse_table(table: str) -> List[List[str]]:
    """Parse table from tabulate into a list of rows."""

    # Filter out frame
    text_lines = [line for line in table.splitlines() if re.search("[A-Za-z]", line)]
    # Remove separators
    sep_regex = r"[|│,]"
    rows = [re.split(sep_regex, line) for line in text_lines]
    return [[val.strip() for val in row if val] for row in rows]


@pytest.fixture
def temp_repo():
    """Setup a temporary renku repository and tear it down."""
    path = tempfile.TemporaryDirectory()
    os.chdir(path.name)
    subprocess.call(["renku", "init", "-t", "python-minimal"])
    yield path.name
    shutil.rmtree(path.name)


@pytest.mark.usefixtures("temp_repo")
def test_ls_samples_empty():
    runner = CliRunner()
    result = runner.invoke(rbc.ls_samples)
    table = parse_table(result.stdout)
    assert result.exit_code == 0
    assert table == [["name", "taxon"]]


@pytest.mark.usefixtures("temp_repo")
def test_ls_samples_one_name():
    runner = CliRunner()
    result = runner.invoke(rbc.add_sample, ["demo1"])
    result = runner.invoke(rbc.ls_samples)
    table = parse_table(result.stdout)
    assert result.exit_code == 0
    assert table == [["name", "taxon"], ["demo1", ""]]


@pytest.mark.usefixtures("temp_repo")
def test_ls_samples_one_full():
    runner = CliRunner()
    result = runner.invoke(
        rbc.add_sample, ["demo1", "--taxon", "taxon1", "--no-prompt"]
    )
    result = runner.invoke(rbc.ls_samples)
    table = parse_table(result.stdout)
    assert result.exit_code == 0
    assert table == [["name", "taxon"], ["demo1", "taxon1"]]


@pytest.mark.usefixtures("temp_repo")
def test_add_sample():
    ...


@pytest.mark.usefixtures("temp_repo")
def test_add_sample_exist():
    ...


@pytest.mark.usefixtures("temp_repo")
def test_show_sample():
    ...


@pytest.mark.usefixtures("temp_repo")
def test_add_rm_sample():
    ...


@pytest.mark.usefixtures("temp_repo")
def test_add_rm_sample_noexist():
    ...
