#!/usr/bin/env python
#
# search - search charm store for a charm.
#

import argparse
import sys
import urllib

import logging
import textwrap
import time

import json
import yaml

VALID_FORMATS = ('text', 'json', 'yaml')
SEARCH_URL_TEMPLATE = 'http://jujucharms.com/search/json?search_text=%s'


def format_text(results):
    print "Results: %d of %d Query: %0.4fs Search: %0.2fs" % (
        results['matches'],
        results['charm_total'],
        results['search_time'],
        results['total_time'])

    idx = 1
    for i in results['results']:
        if i['owner'] == 'charmers':
            label = "cs:%s/%s" % (i['series'], i['name'])
        else:
            label = "cs:~%s/%s/%s" % (i['owner'], i['series'], i['name'])
        print "%s:" % idx, label, i['summary'][:60]
        idx += 1

def main():
    """
    Search for a charm.

    Defaults to a full text search through name, summary, and description.

    Also allows for field level searches on the following::

     - series:<value>  Search for a charm in the given series.

     - owner:<value> Search for a charm with the given owner.

     - provides:<value> Find charms that provide the given interface.

     - requires:<value> Find charms that require the given interface.

    Field level searches can be combined ie:

      $ jitsu search owner:lynxman series:precise provides:http requires:mysql

    Search also supports wildcard on full text fields.
    """
    parser = argparse.ArgumentParser(
        description=textwrap.dedent(main.__doc__),
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument("-f", "--format", default="text",
                        help="Result format (text, json, yaml)")
    parser.add_argument("search_text", nargs="+", help="Query")
    options = parser.parse_args()

    if not options.format in VALID_FORMATS:
        print "Invalid search result format"
        sys.exit(1)

    log_options = {
        "level": logging.DEBUG,
        "format": "%(asctime)s %(name)s:%(levelname)s %(message)s"}

    logging.basicConfig(**log_options)
    search = urllib.quote_plus(" ".join(options.search_text))
    search_url = SEARCH_URL_TEMPLATE % search

    stime = time.time()
    stream = urllib.urlopen(search_url)
    results = json.loads(stream.read())
    results['total_time'] = time.time() - stime
    if options.format == "yaml":
        print yaml.safe_dump(results)
    elif options.format == "json":
        print json.dumps(results, indent=2)
    elif options.format == "text":
        format_text(results)


if __name__ == '__main__':
    main()
