#!/usr/bin/env python3

# Copyright 2012-3, Sean B. Palmer
# Source: http://inamidst.com/saxo/

import os
import re
import saxo

regex_title = re.compile(r"(?ims)<title>(.*?)</title>")
regex_tag = re.compile(r"<[^>]+>")

@saxo.pipe
def title(arg):
    if not arg:
        # TODO: Could put this logic in saxo.pipe
        if "SAXO_URL" in os.environ:
            arg = os.environ["SAXO_URL"]
        else:
            return "Show the title of an HTML web page"

    # TODO: follow is not working
    page = saxo.request(arg, limit=262144)
    search = regex_title.search(page["text"])
    if search:
        title = search.group(1)
        return regex_tag.sub("", title)
    return "No title found"
