import re


def splitOutput(output):
    """
    Parse output of the fffuu haskel-tool.
    Keys in the list elements:
        - action
        - protocol
        - source
        - destination
        - source
        - inInterface (Optional)
        - outInterface (Optional)
        - destPorts (Optional)
        - srcPorts (Optional)

    :param output: Output of fffuu
    :type output: str

    :returns: List of dictionaries with the content of each firewall rule
    :rtype: list<dict>
    """
    output = re.split("== to simple firewall ==", output)[1]
    output = re.split("== to even-simpler firewall ==", output)[0]

    result = list()
    for line in re.split("\n", output):
        splitted = [match.group(0) for match in re.finditer(r"([A-Z]+)|([a-zA-Z]+\s)|(\d+\.\d+\.\d+\.\d+/\d+)|(((dports:)|(sports:)) \d+(:\d+)?)|(((out:)|(in:)) [\.a-zA-Z0-9]+)", line)]
        if len(splitted) > 0:
            part = {
                "action" : splitted[0],
                "protocol" : splitted[1].replace(" ", ""),
                "source" : splitted[2],
                "destination" : splitted[3],
                "inInterface" : None,
                "outInterface" : None,
                "destPorts" : None,
                "srcPorts" : None
            }
            if len(splitted) > 4:
                for match in splitted[4:]:
                    if "in:" in match:
                        part["inInterface"] = match[4:]
                    if "out:" in match:
                        part["outInterface"] = match[5:]
                    if "dports:" in match:
                        match = match[8:]
                        if ":" in match:
                            r = re.split(":", match)
                            part["destPorts"] = list(range(int(r[0]), int(r[1]) + 1))
                        else:
                            part["destPorts"] = [int(match)]
                    if "srcports:" in match:
                        match = match[8:]
                        if ":" in match:
                            r = re.split(":", match)
                            part["srcports"] = list(range(int(r[0]), int(r[1]) + 1))
                        else:
                            part["srcports"] = [int(match)]
            result.append(part)
    return result