#!/usr/bin/env python
#
# Copyright (c) 2005-2011 by Ron Frederick <ronf@timeheart.net>.
# All rights reserved.
# 
# License is granted to copy, to use, and to make and use derivative works
# for non-commercial purposes, provided that this copyright notice and
# contact information is left intact in all such works and any altered
# versions of the source are clearly marked as such.
# 
# This software is provided "AS IS", without warranty of any kind, express
# or implied. In no event shall the author be held liable for any damages
# in connection with this software or the use or other dealings in this
# software.
#
# ************************************************************************
#
# Execute a query against a Data Direct TV Listings database and print
# the results to stdout. Any arguments are given on the command line are
# treated as query terms for a single 'add' command. If no arguments
# are given, a collection of commands is read and executed from stdin.

import shlex, sys, xtvd

if len(sys.argv) > 1:
    query = 'add ' + ' '.join(["'" + arg.replace("'", "\\'") + "'"
                                   for arg in sys.argv[1:]])
else:
    query = sys.stdin

lexer = shlex.shlex(query, posix=True)
lexer.whitespace = ' \t'
lexer.wordchars += '-,'

resultSet = xtvd.ResultSet()

while True:
    cmd = lexer.get_token()
    if not cmd:
        break
    elif cmd == '\r' or cmd == '\n' or cmd == ';':
        continue

    cmd = cmd.lower()

    field = lexer.get_token()
    if not field:
        break

    queryTerms = []

    while field != '\r' and field != '\n' and field != ';':
        if field == 'not':
            negated = True
            field = lexer.get_token()
            if not field:
                break
        else:
            negated = False

        if xtvd.QueryTerm.needsValue(field):
            value = lexer.get_token()
        else:
            value = None

        queryTerms.append(xtvd.QueryTerm(field, value, negated))

        field = lexer.get_token()
        if not field:
            break

    if cmd == 'add':
        resultSet.add(queryTerms)
    elif cmd == 'remove':
        resultSet.remove(queryTerms)
    else:
        print 'Unknown command "%s" ignored.' % cmd

for result in resultSet.fetch():
    xtvd.write(sys.stdout, result)
    print
