import re


def expand_template(input_lines, dist_files):
    """Reads the template starting at the first entry in `input_lines` and generates a copy of it for each
    item in `dist_files` that is not excluded.

    Used by `create_wxs_file`.

    This consumes the lines from the `input_lines` list.

    @param input_lines: The list of input lines from the file, with the first beginning a template expansion
        (should have the <!-- EXPAND_FROM_BIN pragma in it).
    @param dist_files: The list of file entries from the distribution directory.  The template should be expanded
        once for each entry (unless it was specifically excluded).

    @type input_lines: [str]
    @type dist_files:  [{}]

    @return: The list of lines produced by the expansion.
    @rtype: [str]
    """
    # First, see if there were any files that should be excluded.  This will be in the first line, prefaced by
    # EXCLUDED and a comma separated list.
    match = re.search("EXCLUDE:(\S*)", input_lines[0])
    del input_lines[0]

    if match is not None:
        excluded_files = match.group(1).split(",")
    else:
        excluded_files = []

    # Create a list of just the template.  We need to find where it ends in the input lines.
    template_lines = []
    found_end = False
    while len(input_lines) > 0:
        l = input_lines[0]
        del input_lines[0]
        if "<!-- EXPAND_FROM_BIN" in l:
            found_end = True
            break
        else:
            template_lines.append(l)

    if not found_end:
        raise Exception("Did not find termination for EXPAND_FROM_BIN")

    result = []
    # Do the expansion.
    for dist_entry in dist_files:
        if dist_entry["BASE"] in excluded_files:
            continue

        for template_line in template_lines:
            line = template_line.replace("$FILE_ID", dist_entry["FILE_ID"])
            line = line.replace("$COMPONENT_GUID", dist_entry["COMPONENT_GUID"])
            line = line.replace("$COMPONENT_ID", dist_entry["COMPONENT_ID"])
            line = line.replace("$FILE_SOURCE", dist_entry["FILE_SOURCE"])

            result.append(line)

    return result