"""
(C) 2005 Carlo C8E Miron; this program is free software, see http://gnu.org/licenses/gpl.html
$Id: MimeInclude.py 11 2005-04-13 14:15:00Z C8E $

= MimeInclude HTML Test =

== No MIME type (text/plain) ==
MimeInclude(http://www.python.org/~guido/)
----
[[MimeInclude(http://www.python.org/~guido/)]]
----
== HTML ==
MimeInclude(http://www.python.org/~guido/, html)
----
[[MimeInclude(http://www.python.org/~guido/, html)]]
----
== HTML source ==
MimeInclude(http://www.python.org/~guido/, text/html)
----
[[MimeInclude(http://www.python.org/~guido/, text/html)]]
----

= MimeInclude WIKI Test =

== No MIME type (text/plain) ==
MimeInclude(http://projects.edgewall.com/trac/wiki/TracGuide?format=txt)
----
[[MimeInclude(http://projects.edgewall.com/trac/wiki/TracGuide?format=txt)]]
----
== Empty MIME type (wiki rendering) ==
MimeInclude(http://projects.edgewall.com/trac/wiki/TracGuide?format=txt,)
----
[[MimeInclude(http://projects.edgewall.com/trac/wiki/TracGuide?format=txt,)]]
----

= Include Python Test =

== No MIME type (text/plain) ==
MimeInclude(http://projects.edgewall.com/trac/file/trunk/trac/wikimacros/HelloWorld.py?format=txt)
----
[[MimeInclude(http://projects.edgewall.com/trac/file/trunk/trac/wikimacros/HelloWorld.py?format=txt)]]
----
== Python source ==
MimeInclude(http://projects.edgewall.com/trac/file/trunk/trac/wikimacros/HelloWorld.py?format=txt, python)
----
[[MimeInclude(http://projects.edgewall.com/trac/file/trunk/trac/wikimacros/HelloWorld.py?format=txt, python)]]
---
"""
from trac.util import TracError
from trac.WikiFormatter import wiki_to_html
from StringIO import StringIO
from urllib import urlopen

def execute(hdf, text, env):
    args = [x.strip() for x in (text or "").split(",")]
    if len(args) == 1:
        url, mime = args[0], "default"
    elif len(args) == 2:
        url, mime = args
    else:
        raise TracError("MimeInclude requires an URL and an optional mime type as arguments")
    try:
        stream = urlopen(url)
    except IOError, err:
        raise TracError('"%(url)s" is not a valid URL\nError: %(err)s' % vars())
    data = stream.read().strip()
    if mime:
        data = "{{{\n#!%(mime)s\n%(data)s\n}}}" % vars()
    html = wiki_to_html(data, hdf, env, env.get_db_cnx())
    buffer = StringIO(html)
    return buffer.getvalue()
