#!/usr/bin/env python2.7

import xml.etree.ElementTree as ET
from datetime import datetime, tzinfo, timedelta
import time
import cookielib
import urllib
import urllib2
import sys
import os

COOKIE_FILE = os.path.expanduser('~/.is2013wiki-cookie')
ACCESS_TIME_FILE = os.path.expanduser('~/.is2013wiki-accesstime')
INTERVAL_SEC = 300

class LocalTime(tzinfo):
	def utcoffset(self, dt):
		return timedelta(hours=9)

	def tzname(self, dt):
		return "JST"

	def dst(self, dt):
		return timedelta(0)

class UTC(tzinfo):
	def utcoffset(self, dt):
		return timedelta(0)

	def tzname(self, dt):
		return "UTC"

	def dst(self, dt):
		return timedelta(0)

def extract_history(xml_str):
	xml = ET.fromstring(xml_str)

	history = {}
	for item in xml.findall('./{http://purl.org/rss/1.0/}item'):
		title = item.find('./{http://purl.org/rss/1.0/}title').text
		raw_date = item.find('./{http://purl.org/dc/elements/1.1/}date').text
		date = datetime.strptime(raw_date, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo = UTC()).astimezone(LocalTime())
		history[date] = title

	return history

def print_history_from(history, from_time):
	for date in sorted([date for date in history.keys() if date > from_time], reverse = True):
		print('%(title)s -- %(date)s' % {
			'date': date.ctime(),
			'title': history[date]})

def create_cookie(name, password):
	cookie = cookielib.LWPCookieJar()
	opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
	payload = {'action':'login', 'name':name, 'password':password, 'login':'login'}
	payload_encoded = urllib.urlencode(payload)
	response = opener.open('http://is2013.grafi.jp/', payload_encoded)
	if response.read().find('class="error"') < 0:
		return cookie
	else:
		return None

def get_rss(cookie):
	opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
	response = opener.open('http://is2013.grafi.jp/?action=rss_rc&unique=1')
	return response.read()

if (len(sys.argv) >= 2 and sys.argv[1] == 'cookie'):
	name = raw_input('type your username: ')
	password = raw_input('type your password: ')
	cookie = create_cookie(name, password)
	if cookie:
		sys.stderr.write("success\n")
		cookie.save(COOKIE_FILE, True)
		os.chmod(COOKIE_FILE, 0600)
		sys.exit()
	else:
		sys.stderr.write("Acquiring cookie failed. Are username and password correct?\n")
		sys.exit(1)

last_time = datetime.fromtimestamp(0, LocalTime())
if os.path.exists(ACCESS_TIME_FILE):
	with open(ACCESS_TIME_FILE, 'r') as f:
		last_time = datetime.fromtimestamp(float(f.read()), LocalTime())

current_time = datetime.now(LocalTime())
with open(ACCESS_TIME_FILE, 'w') as f:
	f.write(str(time.mktime(current_time.timetuple())))

if timedelta(seconds = INTERVAL_SEC) > current_time - last_time:
	sys.exit()

cookie = cookielib.LWPCookieJar()
cookie.load(COOKIE_FILE, True)
rss = get_rss(cookie)
history = extract_history(rss)

print_history_from(history, last_time)
