'''
Created on Oct 22, 2013

A program that searches Stack Exchange sites for questions with specific tags.

Registered Stack Exchange app: http://stackapps.com/apps/oauth/view/2152

@author: Ryan
'''

import urllib2
import simplejson
import zlib
import sys

key = "i45cYLdEkMGDw4Asznw01w(("
client_id = "2152"
client_secret = "OzWnbQ0nD7NtaoOJJsh5oA(("

# This must be manually generated by going to:
# https://stackexchange.com/oauth/dialog?client_id=2152&redirect_uri=https://stackexchange.com/oauth/login_success
# and approving our app. Then copy the access_token from the address bar.
access_token = "i2H(OEd55TMXekx(Q2kDdQ))"

site = 'stackoverflow'
page = '1'
page_size = '2'
sort_order = 'desc'
sort_value = 'activity'
se_filter = 'withbody'

from_date_2011 = '1319241600'
to_date_2011 = '1319328000'
from_date_2012 = '1350864000'
to_date_2012 = '1350950400'
from_date_2013 = '1382400000'
to_date_2013 = '1382486400'

def get_search_by_tag_json(tag, year):
    from_date = ''
    to_date = ''
    
    if (year == '2011'):
        from_date = from_date_2011
        to_date = to_date_2011
    elif (year == '2012'):
        from_date = from_date_2012
        to_date = to_date_2012
    elif (year == '2013'):
        from_date = from_date_2013
        to_date = to_date_2013
        
    url = 'https://api.stackexchange.com/2.1/search?key=' + key + '&access_token=' + access_token + '&page=' + page + '&fromdate=' + from_date + '&todate=' + to_date + '&order=' + sort_order + '&sort=' + sort_value + '&tagged=' + urllib2.quote(tag) + '&site=' + site + '&filter=' + se_filter
    #print url
    
    response = urllib2.urlopen(url)
    response = response.read()
    #print response
    
    response = zlib.decompress(response, 16 + zlib.MAX_WBITS)
    return response
    
if __name__ == '__main__':
    tag = sys.argv[1]
    year = sys.argv[2]
    
    questions_json = get_search_by_tag_json(tag, year)
    print questions_json
    