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

from icalendar import Calendar
from datetime import datetime
import requests
import pytz


def get_datetimes_array(ics_file):
	''' 
		Gets an ics Calendar file 
		Returns a sorted array of the start dates of the events 
	'''
	g = open(ics_file,'rb')
	ical = Calendar.from_ical(g.read())
	datetimes = []
	for component in ical.walk():
	    if component.name == 'VEVENT':
	        for item in component.sorted_items():
	            if item[0] == 'DTSTART':
	            	datetimes.append(item[1].dt)
	g.close()

	# uncomment the line below if you want to debug like there is a game right now
	# datetimes.append(datetime.utcnow().replace(second=0, microsecond=0, tzinfo = pytz.utc))

	return sorted(datetimes)

def yo_all(api_token):
	return requests.post("http://api.justyo.co/yoall/", data={'api_token': api_token})


def check_if_game_starts_now(games_datetimes, api_token):
	'''
		games_datetimes - an array of datetime objects
		api_token - the api token of the Yo username that sends the Yo to all subscribers
	'''
	# go over the array every minute and see if a game starts now
	upcoming_game = games_datetimes[0]
	stipped_seconds_now = datetime.utcnow().replace(second=0, microsecond=0, tzinfo=pytz.utc) #  we make sure to strip seconds to comparing every minute will work
	if upcoming_game == stipped_seconds_now:
		response = yo_all(api_token)  # found a game start! sends Yo to all THE49ERSGAMEON subscribers!
		print response  


the_49ers_games_datetimes = get_datetimes_array('49ers.ics')  # got this from http://espn.go.com/nfl/team/schedule/_/name/sf/san-francisco-49ers
the_49ers_gameon_token = 'xxxxxxxxxxxxxxxxxxxx'  # this token is generated by contacting us at contact@justyo.co or http://bit.ly/yoapi
check_if_game_starts_now(the_49ers_games_datetimes, the_49ers_gameon_token)  # the_49ers_gameon_token sends a Yo as THE49ERSGAMEON
