#class PrayTimes is in file praytimes.py taken from praytimes.org 

#get  year
#output  
#
#                    year   year 
#                   2019   2020
# Jan 1st   Fajr
#Jan 1st    Dhuhr
#Leap Day
#sudo apt-get install python3-pip
#pip3 install pandas

#attack plan
#Does the muslim prayer time differ by much from year 2020 to 2102
#if not, establish a yearly calendar format for every day of the 5 x 365 
#ANSWER #only 3 minutes of variability in 100 years
#USE pivot table create fake coluumn day of year as index
#flat table
#year month day fajr dhuhr asr maghrib
#2020 05 03   3:33 33:33  3:33
#2088 05 03    3:45  44:3
#need to change 3:33 to an integer 3 + 33/60    or 14:44 = 14 + 44/60
#python3 -m pip install -U matplotlib
#python3 -m pip install -U pytz
#python3 -m pip install -U icalender    for ics support
#webcal allows dynamic calendar events
import pytz
from icalendar import Calendar, Event, Alarm

from praytimes import PrayTimes
from datetime import datetime
import calendar
from datetime import timedelta
import matplotlib.pyplot as plt
import pandas as pd

#dts 5 hours in winter no effect, minus 4 hours summer
offset_utc_dts=-5
#daylight savings = 1 for summer 0 for winter

def is_dst(dt=None, timezone="UTC"):
    if dt is None:
        dt = datetime.utcnow()
    timezone = pytz.timezone(timezone)
    timezone_aware_date = timezone.localize(dt, is_dst=None)
    return timezone_aware_date.tzinfo._dst.seconds 


# Time Names
timeNames = { 
	'imsak'    : 'Time for Imsak Fast',
	'fajr'     : 'Fajr Dawn Prayer Time',
	'sunrise'  : 'Sunrise',
	'dhuhr'    : 'Dhuhr Midday Prayer',
	'asr'      : 'Asr Afternoon Prayer' ,
	'sunset'   : 'Sunset',
	'maghrib'  : 'Maghrib',
	'isha'     : 'Isha Night Prayer',
	'midnight' : 'Midnight'
}

PT = PrayTimes('ISNA')
#longitude and latitude of jane and finch
#43.7573 n, and 79.5177 west

#python has no way of checking use pytz

#format =  24h am pm
#server runs at utc most likely, so subtract 5 hours for Eastern zone Toronto
dtutc=datetime.utcnow()
print(dtutc)
	
FastingSeries = []	
FajrSeries = []
SunriseSeries = []
DhuhrSeries = []
AsrSeries = []
MaghribSeries = []
IshaSeries = []
SunsetSeries=[]
DateSeries = []

yearsInFuture = 1
dayToAddRange = yearsInFuture * 365
#NEED TIME DELTA OR ADD MULTIPLE PLOTS TO SAME GRAPH
#THE DIFFERENCE THROUGHOUT THE YEAR WILL BE TOO SMALL TO SEE THE CYCLE
for dayToAdd in range(dayToAddRange):
	#get date of year + current index
	loopDate = (datetime(2020,1,1,12)+ timedelta(days=dayToAdd ))
	
	
	times = PT.getTimes( (  loopDate.year, loopDate.month , loopDate.day), (43.7573,-79.5177), timezone=0,dst=0, format='24h')
	#print(times["fajr"])
	MINUTES_TO_SUBTRACT = 25
	#fasting time = fajr minus 15 minutes to eat, 10 minutes to dawn = 25 minutes
	#subtract 25 minutes from fajr using time delta
	#convert to time back , always am so 12 hour format doesn't matter
	fajrTime = datetime(loopDate.year, loopDate.month , loopDate.day,    int(times["fajr"].split(":")[0]),   int(times["fajr"].split(":")[1]) )
	sunriseTime = datetime(loopDate.year, loopDate.month , loopDate.day,    int(times["sunrise"].split(":")[0]),   int(times["sunrise"].split(":")[1]) )
	dhuhrTime = datetime(loopDate.year, loopDate.month , loopDate.day,    int(times["dhuhr"].split(":")[0]),   int(times["dhuhr"].split(":")[1]) )
	asrTime = datetime(loopDate.year, loopDate.month , loopDate.day,    int(times["asr"].split(":")[0]),   int(times["asr"].split(":")[1]) )
	sunsetTime = datetime(loopDate.year, loopDate.month , loopDate.day,    int(times["sunset"].split(":")[0]),   int(times["sunset"].split(":")[1]) )
	ishaTime = datetime(loopDate.year, loopDate.month , loopDate.day,    int(times["isha"].split(":")[0]),   int(times["isha"].split(":")[1]) )

	
	fastingTime = 	fajrTime - timedelta(minutes=MINUTES_TO_SUBTRACT )

	FastingSeries.append(fastingTime)
	FajrSeries.append( fajrTime)
	SunriseSeries.append( sunriseTime)
	DhuhrSeries.append( dhuhrTime )
	AsrSeries.append( asrTime)		
	SunsetSeries.append( sunsetTime )
	IshaSeries.append( ishaTime )
	DateSeries.append( loopDate)

##year month day fajr dhuhr asr maghrib
df = pd.DataFrame( {
		"Date" : DateSeries,
		"Fasting" : FastingSeries,
		"Fajr" : FajrSeries,
		"Sunrise" : SunriseSeries,
		"Dhuhr" : DhuhrSeries,
		"Asr" : AsrSeries,
		"Sunset" : SunsetSeries,
		"Isha" : IshaSeries,
		
} 
)
#only 3 minutes of variability in 100 years

print(df.describe())

df["Date"] = pd.to_datetime(df["Date"])



df.to_csv('toronto_all_prayer_times_100_years_dst_24h.csv')


#create an ics file

cal = Calendar()
cal.add('prodid', '-//My calendar product//omarkhan.ca//')
cal.add('version', '2.0')

#loop thru dataframe panda
# iterate through each row and select  
# 'Name' and 'Age' column respectively.
TIME_FORMAT='%Y-%m-%d %H:%M:%S'
for i in range(len(df)) : 
	print(df.loc[i, "Fasting"]) 
	desc_summary = "Fasting" + df.loc[i, "Fasting"].strftime('%B %d, %Y, %r')
	event = Event()
	event.add('summary', 'Fasting Time')
	event.add('dtstart', datetime(  df.loc[i, "Fasting"].year ,
		df.loc[i, "Fasting"].month,
		df.loc[i, "Fasting"].day,
		df.loc[i, "Fasting"].hour,
		df.loc[i, "Fasting"].minute,0,tzinfo=pytz.utc))
	event.add('dtend', datetime(  df.loc[i, "Fasting"].year ,
		df.loc[i, "Fasting"].month,
		df.loc[i, "Fasting"].day,
		df.loc[i, "Fasting"].hour,
		df.loc[i, "Fasting"].minute,0,tzinfo=pytz.utc))
	#event.add('dtstamp', datetime(2005,4,4,0,10,0,tzinfo=pytz.utc))
	
	
	
	#add alarm subcomponent
	alarm = Alarm()
	alarm.add('trigger', timedelta(minutes=-1))
	alarm.add('action', 'display')
	alarm.add('description', desc_summary)
	event.add_component(alarm)
	
	cal.add_component(event)

#write ics file out
f = open('Toronto_All_Prayer_Times_Icalendar_Format.ics', 'wb')
print(cal.to_ical())
f.write(cal.to_ical())
f.close()
print(f)