import ftplib
from typing import Optional
from typing import List


def mlst(connection: ftplib.FTP, filename: str, facts: Optional[List[str]] = None):
    """
    Executes mlst command on the server.

    :param connection: to the server
    :param filename: filename
    :param facts: see ftplib.mlsd doc
    :return:
    """
    # pylint: disable=too-many-locals
    fact_lst = [] if facts is None else facts

    if fact_lst:
        connection.sendcmd("OPTS MLST " + ";".join(fact_lst) + ";")

    resp = connection.sendcmd("MLST {}".format(filename))
    lines = resp.split('\n')

    if len(lines) <= 1:
        raise ftplib.Error("Unexpected number of lines in an MLST response: {!r}".format(resp))

    line = lines[1].lstrip(' ')

    line_parts = line.split(' ')
    if len(line_parts) != 2:
        raise ftplib.Error("Unexpected partition of MLST fact line by space: {!r}".format(resp))

    facts_found, pth = line_parts
    facts_found = facts_found.rstrip(';')

    parts = facts_found.split(';')
    entry = {}
    for part in parts:
        fact_parts = part.split('=')
        if len(fact_parts) != 2:
            raise ftplib.Error("Unexpected partition of MLST fact line by equal sign: {!r}".format(resp))

        key, value = fact_parts
        entry[key.lower()] = value

    return pth, entry