import html


def get_filetype_link(link_text, url, filetype):
    """
    Put the pieces together and produce a valid hyperlink for given output
    filetype.

    Args:
        link_text: A string representing the displayed or linked text when
            linking to something, e.g. "hello" in <a
            href="http://example.org">hello<a>. This string should already be in
            the intended form; i.e. all HTML escapes should have been unescaped
            at this point.
        url: A string of the URL.
        filetype: A string of the output filetype. Accepted parameters are:
            "none", "html", "markdown", "tex", "latex".

    Returns:
        A string that is a valid hyperlink for the specified output filetype.
    """
    if filetype == "markdown":
        # From http://pandoc.org/README.html#backslash-escapes
        # There is also the hyphen, "-", but I've removed that since
        # escaping it just prevents em- and en-dashes from forming (and
        # in most cases, this is what one wants)
        special_chars = "\\`*_{}[]()>#+.!"
        result = ""
        for c in link_text:
            if c in special_chars:
                result += "\\" + c
            else:
                result += c
        return "[{link_text}]({url})".format(link_text=result, url=url)
    if filetype == "html":
        return '<a href="{url}">{link_text}</a>'.format(url=url,
                link_text=html.escape(link_text))
    if filetype == "mediawiki":
        return "[{url} {link_text}]".format(url=url,
                link_text=link_text)
    if filetype in ["latex", "tex"]:
        # LaTeX is really sensitive about special characters so this
        # probably needs a lot of tweaking
        special_chars = "$&%{_#"
        result = ""
        for c in link_text:
            if c in special_chars:
                result += "\\" + c
            elif c == "\\":
                result += "\\textbackslash{}"
            elif c == "~":
                result += "\\textasciitilde{}"
            else:
                result += c
        clean_url = ""
        for c in url:
            if c in special_chars or c in "~":
                clean_url += "\\" + c
            elif c == "\\":
                clean_url += "{\\textbackslash}"
            else:
                clean_url += c
        return ("\\href{%s}{%s}" % (clean_url, result))
    else:
        return "{link_text}: {url}".format(url=url, link_text=link_text)