#!/usr/bin/env python2
# -*- coding: utf-8 -*-

"""
Interface with AUR for packages.
"""

import sys
import argparse
import json
import urllib
import logging
import contextlib


class QueryType(object):

    def __init__(self, term):
        self.logger = logging.getLogger('aursearch')
        self.term = term
        self.emphasis_color = '\033[1;33m'
        self.normal_color = '\033[0m'

    def url(self, type_):
        """Return the URL for the specified query."""
        url = 'http://aur.archlinux.org/rpc.php'
        url = ''.join([url, '?', 'type=', type_, '&arg=', self.term])
        self.logger.info("URL is %s" % url)
        return url

    def package_to_str(self, package):
        """Return a string describing the package."""
        return 'Package: %s%s%s\nDescription: %s\nURL: %s' % (
            self.emphasis_color,
            package.get('Name'),
            self.normal_color,
            package.get('Description'),
            package.get('URL')
        )


class InfoQuery(QueryType):
    """Query type is info."""

    def __init__(self, term):
        super(InfoQuery, self).__init__(term)
        url = self.url()
        try:
            f = urllib.urlopen(url)
            self.info = json.loads(f.read())
            self.type = self.info.get('type')
            self.results = self.info.get('results')
        finally:
            f.close()
        self.logger.info(self.info)

    def url(self):
        return super(InfoQuery, self).url('info')

    def __unicode__(self):
        if self.type != 'error':
            return unicode(self.package_to_str(self.results))
        else:
            return u"Package %s not found." % self.term


class SearchQuery(QueryType):
    """Query type is search."""

    def __init__(self, term):
        super(SearchQuery, self).__init__(term)
        url = self.url()
        with contextlib.closing(urllib.urlopen(url)) as f:
            self.info = json.loads(f.read())
            self.type = self.info.get('type')
            self.results = self.info.get('results')
        self.logger.info(self.info)

    def url(self):
        return super(SearchQuery, self).url('search')

    def __unicode__(self):
        if self.type != 'error':
            res = u''
            for package in self.results:
                res += self.package_to_str(package) + '\n'
            return res[:-1]
        else:
            return u"Packages matching %s not found" % self.term


def setup_args():
    parser = argparse.ArgumentParser(description='Search AUR for a package')
    parser.add_argument(
        '-i', '--info', action='store_true', default=False,
        help=u'Show information for package'
    )
    parser.add_argument('term', help=u'The term to search for')
    parser.add_argument(
        '-v', '--verbose', action='store_true', help=u'Be verbose'
    )
    return parser.parse_args()

def main():
    try:
        args = setup_args()

        logger = logging.getLogger('aursearch')
        level = args.verbose and logging.INFO or logging.WARNING
        logger.setLevel(level)
        handler = logging.StreamHandler()
        logger.addHandler(handler)

        q = args.info and InfoQuery(args.term) or SearchQuery(args.term)

        print q.__unicode__().encode('UTF-8')

        return 0
    except KeyboardInterrupt, e:
        pass


if __name__ == '__main__':
    sys.exit(main())
