#!/usr/bin/python
"""
yahooboss.py - a simple module to access the yahoo BOSS api for web, news and images
"""

import os, sys, re
import httplib, urllib, urlparse
import simplejson as json

class SearchResult(object):
    '''A SearchResult object as returned by yahoo BOSS API
    '''    
    def __init__(self, params):
        self.__dict__.update(params)


class BOSSAPI(object) :
    """the boss api object is used to implement all sorts of queries over the BOSS API from yahoo"""
    search_vertical = 'web'
    search_appid=''
    search_hostname = 'http://boss.yahooapis.com'
    search_port = 80
    params = {}
            
    
    def __init__(self, appid=None, vertical=None, params=None) : 
        '''creates the boss api search object'''
        if appid :
            self.search_appid = appid
            
        if vertical :
            self.search_vertical = vertical
            
        if params :
            self.params = params
            
            
    def query(self, query_string) :
        '''builds a appid rest query and sends it across'''
        
        # first fill up some basics in the params
        self.params['appid'] = self.search_appid
        
        query_string = '/"%s"?' % urllib.quote(query_string) + urllib.urlencode(self.params)
        search_url = self.search_hostname+ '/ysearch/%s/v1' %(self.search_vertical)+query_string
        
        print search_url
        results = [SearchResult(result) for result in 
                   json.loads(urllib.urlopen(search_url).read())['ysearchresponse']['resultset_web']]
                   
        return results
                
        
if __name__ == '__main__' :
    api = BOSSAPI()
    results = api.query('apple pie')
    
    for result in results :
        print "%s\t%s" % (result.title, result.url)

