####################
# #!/usr/bin/python

# # ILFlayout.py

import wx
import os
import sys
from datetime import datetime
from datetime import timedelta as td
# import ilfmain_lossInfo_test


	

def remove_duplicates(values):
    output = []
    seen = set()
    for value in values:
        # If value has not been encountered yet,
        # ... add it to both list and set.
        if value not in seen:
            output.append(value)
            seen.add(value)
    return output
	
	
def monthConversion(month):
	months = {"January":1, "February":2, "March":3, "April":4, "May":5, "June":6, "July":7, "August":8, "September":9, "October":10, "November":11, "December":12}
	for m in months:
		# print m
		if m == month:
			return months[m]

def listDates(start_day, start_month, start_hour, end_day, end_month, end_hour, start_year,  end_year):
	
	# print start_day, start_month, start_hour, end_day, end_month, end_hour, start_year,  end_year
	
	day1 = datetime(start_year, monthConversion(start_month), start_day, start_hour, 00)
	day2 = datetime(end_year, monthConversion(end_month), end_day, end_hour, 00)
	
	delta = day2 - day1
	d1 = day1
	# print delta
	dates = []
	if day1>=day2:
		day2 = day1
		dates.append(day1)
		# return dates
	else:
		if delta.days != 0:
			# print delta.days
			# print delta.seconds/3600
			d1_ = d1
			for i in range(delta.days):
				d2 = d1 + td(days=i)
				# print d2
				for i in range(24):
					d1_ =  d2 + td(hours=i)
					# print d1_
					dates.append(d1_)
			if d1_ >= d1:
				for i in range(1,delta.seconds/3600+2):
					d2 = d1_ + td(hours=i)
					# print d2
					dates.append(d2)
					# raw_input()
		else:
			
			for i in range(0,delta.seconds/3600+1):
				d2 = d1 + td(hours=i)
				# print d2
				dates.append(d2)
				# raw_input()
	# for i in dates:
		# print i
		# temp = i.strftime("%d %m %Y %B %H%M")
		# print temp
		# temp1 = temp.split("-")
		# print temp1[0], temp1[1], temp1[2], temp1[3]
	
	return dates
	
	
# listDates(start_day=01, start_month=monthConversion("December"), start_hour=05, end_day=03, end_month=monthConversion("December"), end_hour=07, start_year=2017,  end_year=2017)
	
	
class MyFrame(wx.Frame):
	def __init__(self, parent, id, title):
		wx.Frame.__init__(self, parent, id, title, (-1, -1), wx.Size(700, 500))
		hbox = wx.BoxSizer(wx.HORIZONTAL)
		

		self.inputdir = os.path.join(os.getcwd(), 'Input Files')
		
		# self.GenMappingFiles = [os.path.join(dir, 'Gen_Mapping_December_01Apr2017.xlsx'),]
		# self.EMMOFiles = [os.path.join(dir, 'EMMO_December_Full_02Apr2017.xlsx'),]
		# self.caseFiles = [os.path.join(dir,"December_2017_Topology Case_22Mar2017.sav"),]
		# self.loadDataFiles = [os.path.join(dir, 'Load Data_December_16Mar2017.xlsx'),]
		# self.loadMappingFiles = [os.path.join(dir, 'Load_Mapping_December_01Apr2017.xlsx'),]
		# self.tssDataFiles = [os.path.join(dir, 'TSS Volumes_December 2015.xlsx'),]
		
		# GenMappingFiles = [os.path.join(dir, 'Gen_Mapping_December_01Apr2017.xlsx'),]
		# EMMOFiles = [os.path.join(dir, 'EMMO_December_Full_02Apr2017_01_06.xlsx'),]
		# caseFiles = [os.path.join(dir,"December_2017_Topology Case_22Mar2017.sav"),]
		# loadDataFiles = [os.path.join(dir, 'Load Data_December_16Mar2017.xlsx'),]
		# loadMappingFiles = [os.path.join(dir, 'Load_Mapping_December_01Apr2017.xlsx'),]
		# tssDataFiles = [os.path.join(dir, 'TSS Volumes_December 2015.xlsx'),]
		
		
		self.YY = 2016
		self.HH1 = 0
		self.DD1 = 0
		self.MM1 = ''
		self.HH2 = 0
		self.DD2 = 0
		self.MM2 = ''
		self.dates = []
		# d1 = datetime(2017,12,01,0,0)
		# self.dates.append(d1)
		self.selectedMonths = []
		
		########## PANEL 1 ##############
		#######################################
		panel1 = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
		hbox_p1 = wx.BoxSizer(wx.VERTICAL)
		
		box1 = wx.BoxSizer(wx.VERTICAL)
		box_action = wx.BoxSizer(wx.VERTICAL)
		hbox_p1.Add( box1, 1, wx.EXPAND, 5 )
		hbox_p1.Add( box_action, 1, wx.EXPAND, 5 )
		
		# box1 = box_input
		self.inputdir_button = wx.Button(panel1, -1, 'Browse')
		# self.s1cases_button = wx.Button(panel1, -1, 'Select State-1 Cases')
		
		# self.m_staticText_inputdir1 = wx.StaticText( panel1, wx.ID_ANY, u"AESO ILF (State-1)", wx.DefaultPosition, wx.DefaultSize, 0 )
		self.m_staticTextTitle = wx.StaticText( panel1, wx.ID_ANY, u"AESO ILF (State-1)", wx.DefaultPosition, wx.DefaultSize, 0 )
		self.m_staticTextTitle.Wrap( -1 )
		self.m_staticTextTitle.SetFont( wx.Font( 16, wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_BOLD, False, wx.EmptyString ) )
		
		self.m_staticText_inputdir2 = wx.StaticText( panel1, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0 )
		self.m_staticText_inputdir3 = wx.StaticText( panel1, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0 )
		self.m_staticText_inputdir4 = wx.StaticText( panel1, wx.ID_ANY, u"Input Files Directory Path", wx.DefaultPosition, wx.DefaultSize, 0 )
		self.m_staticText_inputdir5 = wx.StaticText( panel1, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0 )
		self.m_staticText_inputdir6 = wx.StaticText( panel1, wx.ID_ANY, u"", wx.DefaultPosition, wx.DefaultSize, 0 )
		self.m_textCtr_inputdir = wx.TextCtrl( panel1, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 )
		box1.Add(self.m_staticTextTitle, 0,  wx.ALIGN_CENTER|wx.ALL, 5)
		box1.Add(self.m_staticText_inputdir2, 0,  wx.ALIGN_CENTER|wx.ALL, 5)
		box1.Add(self.m_staticText_inputdir3, 0,  wx.ALIGN_CENTER|wx.ALL, 5)
		box1.Add(self.m_staticText_inputdir4, 0,  wx.ALIGN_CENTER|wx.ALL, 5)
		
		box1.Add(self.m_textCtr_inputdir, 0,  wx.ALIGN_CENTER|wx.EXPAND|wx.ALL, 5)
		box1.Add(self.inputdir_button, 0,  wx.ALIGN_CENTER|wx.ALL, 5)
		
		box_action.Add(self.m_staticText_inputdir5, 0,  wx.ALL, 5)
		box_action.Add(self.m_staticText_inputdir6, 0,  wx.ALL, 5)
		# box1.Add(wx.Button(panel1, 16, 'Topology Case'), 0, wx.ALL|wx.EXPAND, 5)
		# box1.Add(wx.Button(panel1, 11, 'EMMO File'), 0, wx.ALL|wx.EXPAND, 5)
		# box1.Add(wx.Button(panel1, 13, 'Gen Mapping'), 0, wx.ALL|wx.EXPAND, 5)
		# box1.Add(wx.Button(panel1, 12, 'Load Mapping'), 0, wx.ALL|wx.EXPAND, 5)
		# box1.Add(wx.Button(panel1, 14, 'Load Data'), 0, wx.ALL|wx.EXPAND, 5)
		# box1.Add(wx.Button(panel1, 15, 'TSS Data'), 0, wx.ALL|wx.EXPAND, 5)
		
		self.prepCase = wx.Button(panel1, -1, 'Start State-1')
		box_action.Add(self.prepCase,0, wx.ALIGN_CENTER|wx.ALL, 5)
		# box1.Add(self.s1cases_button,0, wx.ALIGN_CENTER|wx.ALL, 5)
		
		self.ModuleGetLossInfo = wx.Button(panel1, -1, 'Exit')
		box_action.Add(self.ModuleGetLossInfo,0, wx.ALIGN_CENTER|wx.ALL, 5)
		
		
		panel1.SetSizer(hbox_p1)
		
		
		############### EVENT DESCRIPTIONS ##############
		self.Bind (wx.EVT_BUTTON, self.OnInputDir, self.inputdir_button)
		# self.Bind (wx.EVT_BUTTON, self.OnEMMO, id=11)
		# self.Bind (wx.EVT_BUTTON, self.OnLoadMapping, id=12)
		# self.Bind (wx.EVT_BUTTON, self.OnGenMapping, id=13)
		# self.Bind (wx.EVT_BUTTON, self.OnLoadData, id=14)
		# self.Bind (wx.EVT_BUTTON, self.OnTSSData, id=15)
		# self.Bind (wx.EVT_BUTTON, self.OnTopologyCaseData, id=16)
		
		################ PANEL 2 #######################
		panel2 = wx.Panel(self, -1, style=wx.SIMPLE_BORDER)
		
		############################################
		self.staticboxDate1 = wx.StaticBox(panel2, -1, "Select Start Date" )
		
		months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
		# self.combobox_month1 = wx.ComboBox(panel2, id = -1, value = 12, size=(150, -1), choices=months, style=wx.CB_DROPDOWN, name="ComboBoxMonth")
		self.combobox_month1 = wx.ComboBox(panel2, id = -1, value = "Select Month", size=(150, -1), choices=months, style=wx.CB_DROPDOWN, name="ComboBoxMonth")
		
		# self.sc_dd1 = wx.SpinCtrl(panel2, -1, value = 1, min = 1, max = 31)
		self.sc_dd1 = wx.SpinCtrl(panel2, -1, value = 'Select Day', min = 1, max = 31)
		# self.sc_hh1 = wx.SpinCtrl(panel2, -1, value = 3, min = 1, max = 24)
		self.sc_hh1 = wx.SpinCtrl(panel2, -1, value = 'Select Hour', min = 0, max = 23)
		
		
		########################### PANEL 2###################
		
		self.staticboxDate2 = wx.StaticBox(panel2, -1, "Select End Date" )
		
		months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
		self.combobox_month2 = wx.ComboBox(panel2, id = -1, value = "Select Month", size=(150, -1), choices=months, style=wx.CB_DROPDOWN, name="ComboBoxMonth")
		
		years = range(2016,2017)
		yrs = []
		for yr in years:
			yrs.append(str(yr))
		self.combobox_year = wx.ComboBox(panel2, id = -1, value = "Select Year", size=(150, -1), choices=yrs, style=wx.CB_DROPDOWN, name="ComboBoxMonth")
		# self.combobox_year = wx.ComboBox(panel2, id = -1, value = 2017, size=(150, -1), choices=yrs, style=wx.CB_DROPDOWN, name="ComboBoxMonth")
		
		
		self.sc_dd2 = wx.SpinCtrl(panel2, -1, value = 'Select Day', min = 1, max = 31)
		self.sc_hh2 = wx.SpinCtrl(panel2, -1, value = 'Select Hour', min = 0, max = 23)
		
		
		#######################  ########################
		
		lblList = ['Manual Selection', 'Range Selection']     
		self.rbox1 = wx.RadioBox(panel2,label = 'Selection Option', pos = (80,10), choices = lblList, majorDimension = 1, style = wx.RA_SPECIFY_COLS)
		self.rbox1Selection = self.rbox1.GetStringSelection()
		# print self.rbox1Selection
		
		box_date1 = wx.StaticBoxSizer(self.staticboxDate1, wx.VERTICAL)
		box_date2 = wx.StaticBoxSizer(self.staticboxDate2, wx.VERTICAL)
		
		# box2.Add(self.staticboxDate1,0,wx.ALL, 5)
		# box2.Add(self.labelStartDate)
		box_date1.Add(self.combobox_month1,0, wx.ALL, 5)
		box_date1.Add(self.sc_dd1,0, wx.ALL, 5)
		box_date1.Add(self.sc_hh1,0, wx.ALL, 5)
		# box_date1.Add(self.combobox_year,0, wx.ALL, 5)
		
		box_date2.Add(self.combobox_month2,0, wx.ALL, 5)
		box_date2.Add(self.sc_dd2,0, wx.ALL, 5)
		box_date2.Add(self.sc_hh2,0, wx.ALL, 5)
		
		self.ButtonCreateDates = wx.Button(panel2, -1, 'Add Dates')
		self.ButtonClearDates = wx.Button(panel2, -1, 'Clear Dates')
		vbox_date = wx.BoxSizer(wx.VERTICAL)
		vbox_date.Add(box_date1, 0,  wx.ALIGN_CENTER|wx.ALL, 5)
		vbox_date.Add(box_date2, 0,  wx.ALIGN_CENTER|wx.ALL, 5)
		vbox_date.Add(self.combobox_year,0,  wx.ALIGN_CENTER|wx.ALL, 5)
		vbox_date.Add(self.rbox1, 0,  wx.ALIGN_CENTER|wx.ALL, 5)
		vbox_date.Add(self.ButtonCreateDates, 0,  wx.ALIGN_CENTER|wx.ALL, 5)
		vbox_date.Add(self.ButtonClearDates, 0,  wx.ALIGN_CENTER|wx.ALL, 5)
		# vbox_date2.Disable()
		panel2.SetSizer(vbox_date)
		
		############# Binding Events ###############
		
		self.Bind (wx.EVT_BUTTON, self.onPrepareCase, self.prepCase)
		self.Bind (wx.EVT_BUTTON, self.onNext, self.ModuleGetLossInfo)
		# self.Bind (wx.EVT_BUTTON, self.onSelectTime, id=18)
		self.Bind (wx.EVT_COMBOBOX, self.onSelectMonth1, self.combobox_month1)
		self.Bind (wx.EVT_SPINCTRL, self.onSelectDay1, self.sc_dd1)
		self.Bind (wx.EVT_SPINCTRL, self.onSelectHour1, self.sc_hh1)
		self.Bind (wx.EVT_COMBOBOX, self.onSelectMonth2, self.combobox_month2)
		self.Bind (wx.EVT_COMBOBOX, self.onSelectYear, self.combobox_year)
		self.Bind (wx.EVT_SPINCTRL, self.onSelectDay2, self.sc_dd2)
		self.Bind (wx.EVT_SPINCTRL, self.onSelectHour2, self.sc_hh2)
		
		self.Bind (wx.EVT_RADIOBOX, self.onSelectRadioBox1, self.rbox1)
		self.Bind (wx.EVT_BUTTON, self.onCreateDates, self.ButtonCreateDates)
		self.Bind (wx.EVT_BUTTON, self.onClearDates, self.ButtonClearDates)
		
		################ Add Panel 1,2 , 3 to hbox
		hbox.Add(panel1, 2, wx.EXPAND | wx.ALL, 0)
		hbox.Add(panel2, 1, wx.EXPAND | wx.ALL, 0)
		# hbox.Add(panel3, 1, wx.EXPAND | wx.ALL, 0 )
		
		############## Frame Set Sizer #########
		# self.SetSize((400, 120))
		self.SetSizer(hbox)
		self.Centre()
	
	def onNext(self, event):
		# self.Hide()
		self.Destroy()
		# import ilfmain_lossInfo
		# self.secondWindow = ilfmain_lossInfo.main()
		# self.Bind(wx.EVT_CLOSE, self.on_close, self.secondWindow)
		
		
	def on_close(self, event):
		closed_window = event.EventObject
		if closed_window == self.secondWindow:
			self.secondWindow = None
			self.Show()
		elif closed_window == self:
			print '===='
			# event.Skip()	
		
	def onClearDates(self, event):
		self.dates = []
		self.selectedMonths = []
		print "Dates cleared"
	def onCreateDates(self, event):
	# def onCreateDates(self):
		
		# self.dates = []
		rbox1Selection = self.rbox1Selection
		
		if rbox1Selection == 'Range Selection':
			print rbox1Selection
			self.dates = []
			# print self.DD1, self.MM1, self.HH1, self.DD2, self.MM2, self.HH2, self.YY,  self.YY
			self.dates = listDates(self.DD1, self.MM1, self.HH1, self.DD2, self.MM2, self.HH2, start_year=self.YY,  end_year=self.YY)
		elif rbox1Selection == 'Manual Selection':
			print rbox1Selection
			d1 = datetime(self.YY, monthConversion(self.MM1), self.DD1, self.HH1)
			# d2 = d1.strftime("%d %m %Y %B %H%M")
			# print d2
			self.dates.append(d1)
		self.dates = remove_duplicates(self.dates)
		for date in self.dates:
			self.selectedMonths.append(date.strftime("%b").upper())
		self.selectedMonths = remove_duplicates(self.selectedMonths)
		
		# print self.dates
		print "======================"
		print "Selected Dates :"
		for i in self.dates:
			print i
		print "Selected Months : "
		print self.selectedMonths
		# for date in self.dates:
			# d = date.split(" ")
			# print d2[3]
			
	
	
	
	def onSelectRadioBox1(self, event):
		self.rbox1Selection =  self.rbox1.GetStringSelection()
		self.dates = []
		self.selectedMonths = []
		
	def onSelectYear(self, event):
		# self.MM = event.GetValue()
		self.YY = int(self.combobox_year.GetValue())
		# print self.YY
	
	def onSelectMonth1(self, event):
		# self.MM = event.GetValue()
		self.MM1 = self.combobox_month1.GetValue()
		# print self.MM1
	def onSelectDay1(self, event):
		self.DD1 = self.sc_dd1.GetValue()
		# print self.DD1
	def onSelectHour1(self, event):
		self.HH1 = self.sc_hh1.GetValue()
		# print self.HH1
	
	def onSelectMonth2(self, event):
		# self.MM = event.GetValue()
		self.MM2 = self.combobox_month2.GetValue()
		# print self.MM2
	def onSelectDay2(self, event):
		self.DD2 = self.sc_dd2.GetValue()
		# print self.DD2
	def onSelectHour2(self, event):
		self.HH2 = self.sc_hh2.GetValue()
		# print self.HH2
		
		
	def onSelectTime(self, event):
		print self.MM1 
		print self.HH1 
		print self.DD1 
		print self.MM2 
		print self.HH2 
		print self.DD2 
		
		
	def OnInputDir(self, event):
		
		wildcard = ""
		dlg = wx.DirDialog(None, "Browse for Input Files directory",style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
		if dlg.ShowModal() == wx.ID_OK:
			self.inputdir =  dlg.GetPath()
			self.m_textCtr_inputdir.SetValue(str(self.inputdir))
		print "Selected Input Folder : "
		print self.inputdir
		# dlg = wx.FileDialog(self, "Choose Input Directory", os.getcwd(), "", wildcard, wx.FD_OPEN)
		# if dlg.ShowModal() == wx.ID_OK:
			# print dlg.GetPath()
			# self.inputdir =  dlg.GetPath()
			
		dlg.Destroy()
	
	def onPrepareCase(self, event):
		# print self.dates
		import BasecasePrep
		
		# raw_input()
		# BasecasePrep.ilf_main(self.caseFiles, self.GenMappingFiles, self.EMMOFiles, self.loadDataFiles, self.loadMappingFiles, self.tssDataFiles, self.dates, self.selectedMonths)
		# BasecasePrep.ilf_main(self.dates, self.selectedMonths)
		BasecasePrep.ilf_main(self.dates, self.selectedMonths, self.inputdir)
	
	def OnEMMO(self, event):
		# wildcard="Text Files (*.txt)|*.txt"
		wildcard = "*.xlsx"
		self.EMMOFiles = []
		dlg = wx.FileDialog(self, "Choose EMMO file", os.getcwd(), "", wildcard, wx.FD_MULTIPLE)
		if dlg.ShowModal() == wx.ID_OK:
			files =  dlg.GetPaths()
			for file in files:
				file = str(file)
				print file
				self.EMMOFiles.append(file)
		dlg.Destroy()
		

	def OnLoadMapping(self, event):
		# wildcard="Text Files (*.txt)|*.txt"
		wildcard="*.xlsx"
		self.loadMappingFiles = []
		dlg = wx.FileDialog(self, "Choose Load Mapping file", os.getcwd(), "", wildcard, wx.FD_MULTIPLE)
		if dlg.ShowModal() == wx.ID_OK:
			files =  dlg.GetPaths()
			for file in files:
				file = str(file)
				print file
				self.loadMappingFiles.append(file)
		dlg.Destroy()
		
	def OnGenMapping(self, event):
		# wildcard="Text Files (*.txt)|*.txt"
		wildcard="*.xlsx"
		self.GenMappingFiles = []
		dlg = wx.FileDialog(self, "Choose Gen Mapping file", os.getcwd(), "", wildcard, wx.FD_MULTIPLE)

		if dlg.ShowModal() == wx.ID_OK:
			files =  dlg.GetPaths()
			for file in files:
				file = str(file)
				print file
				self.GenMappingFiles.append(file)
		dlg.Destroy()

	def OnLoadData(self, event):
		# wildcard="Text Files (*.txt)|*.txt"
		wildcard="*.xlsx"
		self.loadDataFiles = []
		dlg = wx.FileDialog(self, "Choose Load Data file", os.getcwd(), "", wildcard, wx.FD_MULTIPLE)
		if dlg.ShowModal() == wx.ID_OK:
			files =  dlg.GetPaths()
			for file in files:
				file = str(file)
				print file
				self.loadDataFiles.append(file)
		dlg.Destroy()


	def OnTSSData(self, event):
		# wildcard="Text Files (*.txt)|*.txt"
		wildcard="*.xlsx"
		self.tssDataFiles = []
		dlg = wx.FileDialog(self, "Choose TSS file", os.getcwd(), "", wildcard, wx.FD_MULTIPLE)
		if dlg.ShowModal() == wx.ID_OK:
			files =  dlg.GetPaths()
			for file in files:
				file = str(file)
				print file
				self.tssDataFiles.append(file)
		dlg.Destroy()
		
	def OnTopologyCaseData(self, event):
		wildcard=""
		self.caseFiles =[]
		# dlg = wx.FileDialog(self, "Choose a file", os.getcwd(), "", wildcard, wx.FD_OPEN)
		dlg = wx.FileDialog(self, "Choose Topology Cases", os.getcwd(), "", "*.sav", wx.FD_MULTIPLE)
		# dlg = wx.FileDialog(self, "Choose a file", "", "", "*.*", wx.FD_MULTIPLE)
		if dlg.ShowModal() == wx.ID_OK:
			files =  dlg.GetPaths()
			for file in files:
				file = str(file)
				print file
				self.caseFiles.append(file)
		dlg.Destroy()
		

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'AESO ILF - Prepare State 1 Cases')
        frame.Show(True)
        return True

app = MyApp(0)
app.MainLoop()
