#!python
#-*- encoding=utf-8 -*-


import sys, sqlite3, logging, os, os.path
import wx, time, re, copy, webbrowser
import wx.grid, wx.html
import json, math

from cfg import config
from util import *
from model import *
from view import *

class App(wx.App):
	instance = None
	def __init__(self, conf, *args):
		wx.App.__init__(self, *args) # do not redirect for now
		self.user = None
		self.cfg  = conf
		self.printer = None
	def OnInit(self):
		return True
	@staticmethod
	def GetInstance():
		return App.instance
	def Quit(self):
		wx.Exit()
		sys.exit()
	def 
(self):
		if not os.path.isfile( self.cfg.datapath ):
			self.setup()
		else:
			self.bootstrap()
		self.checkExpiration()
		AuthFrame(self).Show()
	def bootstrap(self):
		self.dbconn = DB.getInstance().conn
		self.modelUser = ModelUser( self.dbconn )
		self.modelSheet= ModelSheet( self.dbconn )
		self.logger = XLog.getDefaultLogger()
	def setup(self):
		try:
			os.makedirs( os.path.join(self.cfg.rootdir, r'data') )
			os.makedirs( os.path.join(self.cfg.rootdir, r'log') )
			os.makedirs( os.path.join(self.cfg.rootdir, r'cache') )
		except:
			alert( u'程序初始化失败, 即将退出' )
			self.Quit()
		self.bootstrap()
		self.modelUser.initTable()
		self.modelSheet.initTable()
	def checkExpiration(self):
		self.expirationTip  = ''
		return True # skip expiration check
		self.appExpireInDays = self.cfg.expiration
		time0 = self.modelUser.getEarliestDate()
		daysElapsed = 0
		if time0>0:
			daysElapsed = int( (time.time()-time0)/86400 )
		
		if daysElapsed > -1:
			if self.appExpireInDays < daysElapsed:
				self.expire()
			self.appExpireInDays -= daysElapsed
			daysElapsed
			self.expirationTip = u'试用版,{}天后过期'.format(self.appExpireInDays)
		else:
			self.expire(u'×系统时间混乱×\n程序退出')
	def expire(self):
		alert(u'本软件已过期，\n不能继续使用', u'试用过期啦～')
		self.Quit()
	def authOk(self, user):
		self.user = user
		self.cfg.user = user
		mf = MainFrame(parent=None, title=self.user['name'] + u' 你好，欢迎使用本软件') #( {} )'.format(self.expirationTip) )
		mf.app = self
		if self.user.isAdmin():
			ManagerPanel(mf, self)
		else:
			OperatorPanel(mf)
		mf.maxWindow()
	def getPrinter(self):
		if not self.printer:
			self.printer = wx.html.HtmlEasyPrinting()
		return self.printer
	def printSheet(self, sheet):
		# self.printViaHtml( sheet )
		self.getPrinter().GetPrintData().SetPaperSize( wx.Size(-1, 400) )
		self.getPrinter().GetPrintData().PaperSize = wx.Size(-1, 400)
		self.getPrinter().PrintText( self.getSheetHtml(sheet) )
	def getSheetHtml(self, sheet):
		data = sheet.getDict()
		data['bigamount'] = cnNumber( data['amount'] )
		return getPrintTpl().format( **data )
	def printViaHtml(self, sheet):
		filepath = os.path.join(self.cfg.cachepath, "{}.html".format(sheet['id']) )
		file = open(filepath, 'wb')
		file.write( self.getSheetHtml(sheet).encode('utf-8') )
		file.close()
		webbrowser.open(filepath)


# if '__main__'==__name__:

app = App(config, False) # True, os.path.join(ctx.dir, 'run.dat') )
App.instance = app
config.app = app
app.Run()
app.MainLoop()
	

Run