from typing import Callable
from typing import List


def csv_line_reader(separator=",", quoter='"', escaper="\\", strip_chars="\r\t\n ") -> Callable[[str], List[str]]:
    """
    Creates a function that parses a **line** in csv format using the given parameters and returns a list of strings.

    .. warning::
       Quoting a field does not prevent leading and trailing chars to be stripped.
       Therefore parsing `'" here I ",am'` would result in `['here I', 'am']`.

    >>> from pyconnect.config import csv_line_reader
    >>> reader = csv_line_reader()
    >>> line = r'"quoted,field",escaped\,field, stripped field ," quoted \" escaped field"'
    >>> reader(line)
    ['quoted,field', 'escaped,field', 'stripped field', 'quoted " escaped field']

    :param separator: Char used to separate fields.
    :param quoter: Char used to quote a field, separators are ignored within quoted fields.
    :param escaper: Char used to escape to following char, for example when it is a separator.
    :param strip_chars: Those chars are stripped from the beginning and end of each field.
    :return: A parser for csv lines.
    """  # noqa: W605

    def line_reader(input_line: str):
        charlist = list(input_line)
        fields = []
        quoting = False
        escaping = False

        if len(charlist) > 0:
            fields.append("")

        while len(charlist) > 0:
            char = charlist.pop(0)
            if escaping:
                fields[-1] += char
                escaping = False
            elif char == escaper:
                escaping = True
            elif char == quoter:
                quoting = not quoting
            elif char == separator and not quoting:
                fields.append("")
            else:
                fields[-1] += char
        return [field.strip(strip_chars) for field in fields]

    return line_reader