# -*- coding: utf-8 -*-
A “web service” for generating random quotes.

Place this file (along with quotes.py) on your server, execute it through the browser.

When called without arguments, this script produces a quote in standard HTML format. It takes
an optional format parameter, by appending ?format=Format_Name at the end of the URL.

Formats supported so far (case sensitive):
* html — default foramt
* javascript — the script works as a Javascript widget
* json — output is in JSON format, for to use as you want

Widget example:
Place the following in your HTML file: 
<script type='text/javascript' src='URL/to/script?format=javascript' />
A quote will be inserted wherever you’ve placed the script tag.

All the output is utf-8 encoded, and so are the source files.

Required third-party libraries:
* simplejson

Have fun.

__author__ = "Ankit Solanki (ankit@simulacra.in)"
__copyright__ = "Copyright 2006, Ankit Solanki"
__contributors__ = []
__version__ = "1.1"
__license__ = "MIT"
__history__ = """
1.0 — Initial version of the script
1.1 — Refactored the script, created the RandomQuote class.
      Made the code slightly more flexible by adding a method dispatcher in main.
      Also documented the code somewhat.
1.2 — Added proper content types. It was always outputting text/html before, now
      the output is text/html, application/json, text/javascript depending on the mode.
      The Javascript widget now does the ‘right’ thing, no more document.write().

class RandomQuote:

    def getQuote(self):
        Generate a random quote.
        Output is a dictionary, with keys: quote, author, URL.
        Only the quote key is sure to be present"""
        from quotes import quotes, authors
        from random import Random
        quote = quotes[Random().randint(0, len(quotes)-1)]

        if quote.has_key("author") and authors.has_key(quote["author"]):
            quote["URL"] = authors[quote["author"]]

        return quote

    def htmlQuote(self):
        """Outputs a random quote in HTML format."""
        quote = self.getHTMLQuote()

        print "Content-Type: text/html; charset=utf-8"
        print "Status: 200 Ok"

        print quote

    def getHTMLQuote(self):
        """Get a random quote in HTML format."""
        quote = self.getQuote()
        html = quote["quote"]
        if quote.has_key("author") and quote.has_key("URL"):
            html += " — " + "<a href=\"" + quote["URL"] + "\">" + quote["author"] + "</a>"

        return html 

    def jsonQuote(self):
        """Output a random quote in JSON format."""
        quote = self.getQuote()

        print "Content-Type: application/json; charset=utf-8"
        print "Status: 200 Ok"

        import simplejson
        print simplejson.dumps(quote, ensure_ascii=False)

    def javascriptQuote(self):
        """Inserts a random quote into your page using Javascript."""
        javascript = "document.getElementById('quote-div').innerHTML = \"<h2>Random quote</h2><p>"
        javascript += self.__javascriptEscape(self.getHTMLQuote())
        javascript += "</p>\");"

        print "Content-Type: text/javascript; charset=utf-8"
        print "Status: 200 Ok"

        print javascript

    def __javascriptEscape(self, text):
        return text.replace('"', '\\"')

if __name__ == "__main__":
    import cgi
    import cgitb


    obj = RandomQuote()
    form = cgi.FieldStorage()

    if form.has_key("format"):
        format = form["format"].value + "Quote"
        (hasattr(obj, format) and getattr(obj, format) or obj.htmlQuote)()