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

import wx
import sys
import os
import pws

	
class Application(wx.App):
	
	def __init__(self, approot):
		self.approot = approot
		self.server = None
		wx.App.__init__(self)
		
	def OnInit(self):
		
		boot = pws.Initializer(self.approot)
		if not boot.is_ready():
			if not self.one_time_init(boot):
				return False
	
		self.server = pws.Server(self.approot)
		self.server.smart_start_services()
		
		frame = pws.MainFrame()
		self.SetTopWindow(frame)
		frame.Show()
		
		return True
		
		
	def one_time_init(self, boot):
		state, message = boot.get_state()
		if state == pws.Initializer.STATE_NOT_READY:
			# Not ready but because it is not initialized.
			wx.MessageBox("Will perform first-time initialization.\n\nNote: this application requires a one-time initialization step, which will be performed now.\n\n(For your information, I detected that: "+message+")", "First-time initialization", wx.OK | wx.ICON_INFORMATION)
			boot.run()
			state, message = boot.get_state()
			if state != pws.Initializer.STATE_READY:
				wx.MessageBox("One-time initialization failed.\n\nPlease try to run the program again. If the problem persists, please uninstall this program completely, and run the installer again.\n\nError message: "+message+".", "Initialization failed", wx.OK | wx.ICON_ERROR)
				return False
			else:
				wx.MessageBox("One-time initialization succeeded.\n\nThe program will now start normally. You will not see this dialog again.", "Initialization succeeded", wx.OK | wx.ICON_INFORMATION)
				return True
		else:
			if wx.MessageBox("Initializer is not ready, reset is needed.\n\nReason: "+message+"\n\nDo you want to reset the initialization ?\n\nWARNING: If you answer YES, all your PiAnoS data will be erased, and cannot be recovered. If you are unsure about what this means, please answer NO and contact someone who knows before doing something you may regret.\n\nHowever, if you know for sure that no data is present in the database (e.g. you are currently deploying the software for the first time on this system), you can go ahead safely.", "Initialization error", wx.YES_NO | wx.ICON_ERROR) == wx.YES:
				boot.cleanup()
				state, message = boot.get_state()
				if state != pws.Initializer.STATE_NOT_READY:
					wx.MessageBox("Cleanup failed - your installation is corrupted.\n\nSomething went really wrong here. Please uninstall this program completely, and run the installer again.\n\nError message: "+message+".", "Cleanup failed", wx.OK | wx.ICON_ERROR)
				else:
					wx.MessageBox("The program has been reset successfully.\n\nYou can now run the program again to perform the initialization.", "Cleanup succeeded", wx.OK | wx.ICON_INFORMATION)
			return False
		

	
if __name__=='__main__':
	if len(sys.argv) > 1:
		approot = sys.argv[1]
	else:
		approot = '.'
	app = Application(approot)
	app.MainLoop()
