#!/usr/bin/env python
#

"""
gfeed: Display input lines as a "feed"

Example:
  gchat 2> $GTERM_SOCKET 0<&2 | gfeed > $GTERM_SOCKET
"""

import csv
import json
import logging
import os
import sys

from optparse import OptionParser

import gterm

pagelet_html = """<script>
var GTPageletMaxFeeds = 20;
function GTPageletJSON(pageletElem, feed) {
    // Display new feed, sliding it into the top line
    feed = $.trim(feed);
    if (_.str.endsWith(feed, "alerttrue")) {
        gtermAlertUpdate(true);
    } else if (_.str.endsWith(feed, "alertfalse")) {
        gtermAlertUpdate(false);
    } else {
        $('<li>'+feed+'<p></li>').hide().prependTo(pageletElem.find("ul")).slideDown("slow").animate({opacity: 1.0});
        if (pageletElem.find("ul li").length > GTPageletMaxFeeds)
            pageletElem.find("ul li:last-child").remove();
    }
}

</script>
<style>
.gterm-pagelet-gfeeds-container ul {
   list-style: none;
   color: red;
}
</style>
<div class="gterm-pagelet-gfeeds-container">
<ul>
</ul>
</div>
"""

usage = "usage: %prog [-h ...]"
parser = OptionParser(usage=usage)

parser.add_option("-c", "--csv", dest="csv", action="store_true", help="CSV input")
parser.add_option("-j", "--json", dest="json", action="store_true",  help="JSON input")
parser.add_option("", "--opacity", dest="opacity", default=1.0,
                  help="Feed opacity (default: 1.0)")
parser.add_option("", "--owner", dest="owner", action="store_true", help="Display widget for owners only")

(options, args) = parser.parse_args()

add_headers = {}
if options.opacity:
    add_headers["opacity"] = options.opacity

Json_headers = {"content_type": "text/json"}
Json_headers["x_gterm_response"] = "pagelet_json"
Json_headers["x_gterm_parameters"] = {}

if options.owner:
    add_headers["owners_only"] = True
    Json_headers["x_gterm_parameters"]["owners_only"] = True

gterm.write_pagelet(pagelet_html, display="fullscreen", dir=os.getcwd(), add_headers=add_headers)
while True:
    try:
        line = sys.stdin.readline()
        if not line:
            break
        line = line.rstrip()
    except (EOFError, KeyboardInterrupt):
        break
    jcolon = line.find(":")
    jspace = line.find(" ")
    if jcolon > 0 and jcolon < jspace:
        prefix, sep, suffix = line.partition(":")
        feed_html = '<b>%s</b>:%s' % (prefix, suffix)
    else:
        feed_html = line
    gterm.wrap_write(json.dumps(feed_html), headers=Json_headers)

gterm.write_blank()
