#
# Civilization 4: Colonization
# MFinance Mod
# by Melinko
#
#

from CvPythonExtensions import *
import CvScreenEnums
import CvUtil
import CvAlertManager

PIXEL_INCREMENT = 7
BOX_INCREMENT_WIDTH = 27 # Used to be 33 #Should be a multiple of 3...
BOX_INCREMENT_HEIGHT = 9 #Should be a multiple of 3...
BOX_INCREMENT_Y_SPACING = 6 #Should be a multiple of 3...
BOX_INCREMENT_X_SPACING = 9 #Should be a multiple of 3...


############################################################################
# globals
gc = CyGlobalContext()
ArtFileMgr = CyArtFileMgr()
oLocalText = CyTranslator()

oMap = CyMap()
oArtFileMgr = CyArtFileMgr()
alert = CvAlertManager.CvAlertManager()
############################################################################

#Unique Name of the Class. Has to match CvScreenInterface
class CvFinancialAdvisorScreen:
	"A Blank Civ4 Screen"

	def __init__(self):
		#Unique name for the Prefix Name
		self.sWidgetPrefix = "FinancialAdvisorScreen"

		self.MANAGER_SCREEN_ID = self.sWidgetPrefix + "MainWindow"
		self.BACKGROUND_ID = self.sWidgetPrefix + "BackgroundImage"
		self.HEADER_PANEL_ID = self.sWidgetPrefix + "HeaderPanelWidget"
		self.FOOTER_PANEL_ID = self.sWidgetPrefix + "FooterPanelWidget"
		self.HEADER_ID = self.sWidgetPrefix + "HeaderTextWidget"
		self.EXIT_ID = self.sWidgetPrefix + "ExitTextWidget"

		self.TITLE = u"<font=4b>Financial Advisor</font>"

		self.X_SCREEN = 0
		self.Y_SCREEN = 0
		self.W_SCREEN = 1024
		self.H_SCREEN = 768

		self.H_BAR = 55

		self.Z_BACKGROUND = -6.1
		self.Z_CONTROLS = self.Z_BACKGROUND - 0.2

		self.nWidgetCount = 0

		self.initWidgetIDs()
		self.initValues()

	# Screen construction function
	def interfaceScreen(self):
		self.player = gc.getPlayer(gc.getGame().getActivePlayer())

		screen = self.getScreen()

		if (screen.isActive()):
			return None

		self.nScreenWidth = screen.getXResolution()
		self.nScreenHeight = screen.getYResolution()

		self.W_SCREEN = self.nScreenWidth
		self.H_SCREEN = self.nScreenHeight

		screen.setDimensions(self.X_SCREEN, self.Y_SCREEN, self.W_SCREEN, self.H_SCREEN)

		screen.setRenderInterfaceOnly(True);
		screen.setRenderFrozenWorld(True)
		screen.showScreen(PopupStates.POPUPSTATE_IMMEDIATE, False)
		screen.showWindowBackground(True)

		self.initValues()

		iX = 0
		iY = 0

		# Set the background widget and exit button
		screen.addDrawControl(self.BACKGROUND_ID, oArtFileMgr.getInterfaceArtInfo("MAINMENU_SLIDESHOW_LOAD").getPath(), 0, 0, self.nScreenWidth, self.nScreenHeight, WidgetTypes.WIDGET_GENERAL, -1, -1)

		self.showHeader()
		self.showFooter()
		self.makeScrollPanel()
		self.makeCategoryBoxes()
		self.makeCategoryTitleBoxes()

	def initWidgetIDs(self):
		self.SCROLL_PANEL_ID = self.sWidgetPrefix + "ScrollPanel"
		return None

	def initValues(self):
		self.lCategory = []
		return None

	#############################################################################################################

	def getScreen(self):
		return CyGInterfaceScreen(self.MANAGER_SCREEN_ID, CvScreenEnums.FINANCIAL_ADVISOR)

	def hideScreen(self):
		screen = self.getScreen()
		screen.hideScreen()
		return None

	def update(self, fDelta):
		return None

	# handle the input for this screen...
	def handleInput(self, inputClass):
		screen = self.getScreen()
		iNotifyCode = inputClass.getNotifyCode()
		iNotifyClicked = NotifyCode.NOTIFY_CLICKED
		iNotifyChar = NotifyCode.NOTIFY_CHARACTER
		iNotifyListSelect = NotifyCode.NOTIFY_LISTBOX_ITEM_SELECTED
		iReturn = 0

		if (iNotifyCode == iNotifyClicked):
			sInputName = inputClass.getFunctionName()
			if (inputClass.getButtonType() == WidgetTypes.WIDGET_GENERAL and inputClass.getData1() == 1111):
				return 1
		return 0

	#############################################################################################################

	# returns a unique ID for a widget in this screen
	def getNextWidgetName(self):
		szName = self.sWidgetPrefix + str(self.nWidgetCount)
		self.nWidgetCount += 1
		return szName

	def deleteDynamicWidgets(self):
		screen = self.getScreen()
		i = self.nWidgetCount - 1
		while (i >= 0):
			self.nWidgetCount = i
			screen.deleteWidget(self.getNextWidgetName())
			i -= 1

		self.nWidgetCount = 0
		return None

	#############################################################################################################

	def makeScrollPanel(self):
		screen = self.getScreen()
		screen.addScrollPanel(self.SCROLL_PANEL_ID, "Test Text", 0, self.H_BAR, self.W_SCREEN, self.H_SCREEN - (self.H_BAR * 2) -15, PanelStyles.PANEL_STYLE_EXTERNAL, True, WidgetTypes.WIDGET_GENERAL, -1, -1)
		screen.setActivation(self.SCROLL_PANEL_ID, ActivationTypes.ACTIVATE_NORMAL)
		return None

	def makeCategoryBoxes(self):
		screen = self.getScreen()
		iX = 50
		iY = self.H_BAR - 50
		iWidth = self.W_SCREEN - 100
		iHeight = 75
		iPanelStyle = PanelStyles.PANEL_STYLE_IN
		self.lCategory += [self.getNextWidgetName()]
		screen.attachPanelAt(self.SCROLL_PANEL_ID, self.lCategory[0], u"", u"", False, False, iPanelStyle, iX, iY, iWidth, iHeight, WidgetTypes.WIDGET_GENERAL, -1, -1)

		iY += iHeight + 50
		iWidth = (self.W_SCREEN - (50 * 2) - (60 * 2)) / 3
		iHeight = self.H_SCREEN - iY - 50 - self.H_BAR * 2
		for iCount in range(3):
			self.lCategory += [self.getNextWidgetName()]
			iX = (iCount * (50 + iWidth)) + 60
			screen.attachPanelAt(self.SCROLL_PANEL_ID, self.lCategory[iCount + 1], u"", u"", False, False, iPanelStyle, iX, iY, iWidth, iHeight, WidgetTypes.WIDGET_GENERAL, -1, -1)
		return None

	def makeCategoryTitleBoxes(self):
		screen = self.getScreen()

		for iCount in range(len(self.lCategory)):
			if (iCount == 0):
				sTitle = u"<font=4>%s</font>"%(self.getText("TXT_KEY_FINANCIAL_ADVISOR_TREASURY_TEXT", (gc.getActivePlayer().getGold(),)))
				iX = (self.W_SCREEN - (96 * 3)) / 2
				iY = 65
				screen.addDDSGFC("GoldPile", oArtFileMgr.getInterfaceArtInfo("SCREEN_GOLD_PILE").getPath(), iX, iY, 80, 80, WidgetTypes.WIDGET_GENERAL, -1, -1)
				screen.setHitTest("GoldPile",HitTestTypes.HITTEST_NOHIT)

#				iX = (self.W_SCREEN - 100) / 2
#				iY = 30

				iX = (self.W_SCREEN - 96) / 2
				iY = 30
				sTempName = self.getNextWidgetName()
				screen.setTextAt(sTempName, self.lCategory[iCount], sTitle, CvUtil.FONT_CENTER_JUSTIFY, iX, iY, self.Z_CONTROLS, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_GENERAL, -1, -1)
				screen.setHitTest(sTempName, HitTestTypes.HITTEST_NOHIT)

#				iX = 800
#				iY = 65
#				screen.addDDSGFC("GoldPile", oArtFileMgr.getInterfaceArtInfo("SCREEN_GOLD_PILE").getPath(), iX, iY, 80, 80, WidgetTypes.WIDGET_GENERAL, -1, -1)
#				screen.setHitTest("GoldPile",HitTestTypes.HITTEST_NOHIT)

			if (iCount == 1):
				sTitle = u"<font=4>%s</font>"%(self.getText("TXT_KEY_FINANCIAL_ADVISOR_COMMERCE_TEXT"))

			if (iCount == 2):
				sTitle = u"<font=4>%s</font>"%(self.getText("TXT_KEY_FINANCIAL_ADVISOR_INCOME_TEXT"))

			if (iCount == 3):
				sTitle = u"<font=4>%s</font>"%(self.getText("TXT_KEY_FINANCIAL_ADVISOR_EXPENSES"))

			iX = ((self.W_SCREEN - (50 * 2) - (60 * 2)) / 3) / 2
			iY = 15

			if (iCount != 0):
				sTempName = self.getNextWidgetName()
				screen.setTextAt(sTempName, self.lCategory[iCount], sTitle, CvUtil.FONT_CENTER_JUSTIFY, iX, iY, self.Z_CONTROLS, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_GENERAL, -1, -1)
				screen.setHitTest(sTempName, HitTestTypes.HITTEST_NOHIT)

		self.setCommerceText()
		self.setIncomeText()
		self.setExpenses()
		return None

	def setCommerceText(self):
		dCommerce = {}
		lSort = []

		#add here if you want it to be under the Commerce category
		#Too add another entry to the list, all you need to add is The text you want to be shown into DCommerce:Code you want run
		#and the text you want to be shown in lSort (Note where you add it in lSort is where it will be shown
		#It doen't have to be a TXT_KEY.. it only needs to be in ""'s (also known as a string)
		#The text you put into DCommerce HAS to match the text in lSort or it will not show on the screen!

		dCommerce["TXT_KEY_FINANCIAL_ADVISOR_TOTAL_YIELD_STORED"] = self.getTotalCommerceValue()
		dCommerce["TXT_KEY_FINANCIAL_ADVISOR_IMMIGRATION_THRESHOLD"] =  gc.getActivePlayer().immigrationThreshold()
		dCommerce["TXT_KEY_FINANCIAL_ADVISOR_EDUCATION_THRESHOLD"] = gc.getActivePlayer().getPrimaryCity().educationThreshold()
		dCommerce["TXT_KEY_FINANCIAL_ADVISOR_NUMBER_OF_CITIES"] = gc.getActivePlayer().getNumCities()

		lSort += ["TXT_KEY_FINANCIAL_ADVISOR_TOTAL_YIELD_STORED"]
		lSort += ["TXT_KEY_FINANCIAL_ADVISOR_IMMIGRATION_THRESHOLD"]
		lSort += ["TXT_KEY_FINANCIAL_ADVISOR_EDUCATION_THRESHOLD"]
		lSort += ["TXT_KEY_FINANCIAL_ADVISOR_NUMBER_OF_CITIES"]

		self.drawText(1, dCommerce, lSort)
		return None

	def setIncomeText(self):
		dIncome = {}
		lSort = []

		#add here if you want it to be under the Income category
		#Too add another entry to the list, all you need to add is The text you want to be shown into DCommerce:Code you want run
		#and the text you want to be shown in lSort (Note where you add it in lSort is where it will be shown
		#It doen't have to be a TXT_KEY.. it only needs to be in ""'s (also known as a string)
		#The text you put into DCommerce HAS to match the text in lSort or it will not show on the screen!

		if (gc.getActivePlayer().getHighestTradedYield() != -1):
			sHighestTraded = gc.getYieldInfo(gc.getActivePlayer().getHighestTradedYield()).getDescription()
		else:
			sHighestTraded = "None"

		dIncome["TXT_KEY_FINANCIAL_ADVISOR_HIGHEST_TRADED"] = sHighestTraded
		dIncome["TXT_KEY_FINANCIAL_ADVISOR_NUMBER_OF_TRADE_ROUTES"] = gc.getActivePlayer().getNumTradeRoutes()
		dIncome["TXT_KEY_FINANCIAL_ADVISOR_TOTAL_POPULATION"] = gc.getActivePlayer().getTotalPopulation()
		dIncome["TXT_KEY_FINANCIAL_ADVISOR_TOTAL_POPULATION_IN_EUROPE"] = gc.getActivePlayer().getNumEuropeUnits()

		lSort += ["TXT_KEY_FINANCIAL_ADVISOR_HIGHEST_TRADED"]
		lSort += ["TXT_KEY_FINANCIAL_ADVISOR_NUMBER_OF_TRADE_ROUTES"]
		lSort += ["TXT_KEY_FINANCIAL_ADVISOR_TOTAL_POPULATION"]
		lSort += ["TXT_KEY_FINANCIAL_ADVISOR_TOTAL_POPULATION_IN_EUROPE"]

		if (self.getTotalYieldBoughtValue() <= 0):
			dIncome["TXT_KEY_FINANCIAL_ADVISOR_TOTAL_YIELD_SOLD"] = abs(self.getTotalYieldBoughtValue())
			lSort += ["TXT_KEY_FINANCIAL_ADVISOR_TOTAL_YIELD_SOLD"]

		self.drawText(2, dIncome, lSort)
		return None

	def setExpenses(self):
		dExpenses = {}
		lSort = []

		#add here if you want it to be under the Expenses category
		#Too add another entry to the list, all you need to add is The text you want to be shown into DCommerce:Code you want run
		#and the text you want to be shown in lSort (Note where you add it in lSort is where it will be shown
		#It doen't have to be a TXT_KEY.. it only needs to be in ""'s (also known as a string)
		#The text you put into DCommerce HAS to match the text in lSort or it will not show on the screen!

		if (self.getTotalYieldBoughtValue() > 0):
			dExpenses["TXT_KEY_FINANCIAL_ADVISOR_AMOUNT_OF_YIELD_BOUGHT"] = self.getTotalYieldBoughtValue()
			lSort += ["TXT_KEY_FINANCIAL_ADVISOR_AMOUNT_OF_YIELD_BOUGHT"]

		dExpenses["TXT_KEY_FINANCIAL_ADVISOR_CURRENT_TAX"] = gc.getActivePlayer().getTaxRate()
		dExpenses["TXT_KEY_FINANCIAL_ADVISOR_TOTAL_IMPROVEMENT_COST"] = self.getTotalImprovementCostValue()

		lSort += ["TXT_KEY_FINANCIAL_ADVISOR_CURRENT_TAX"]
		lSort += ["TXT_KEY_FINANCIAL_ADVISOR_TOTAL_IMPROVEMENT_COST"]

		self.drawText(3, dExpenses, lSort)

		return None

	def drawText(self, iPanel, dCategory, lSort):
		screen = self.getScreen()
		for iCount in range(len(lSort)):
			iX = 10
			iY = 50 + (iCount * 30)
			sText = "%s: %s"%(self.getText(lSort[iCount]), self.getText(dCategory[lSort[iCount]]))
			sTempName = self.getNextWidgetName()
			screen.setTextAt(sTempName, self.lCategory[iPanel], sText, CvUtil.FONT_LEFT_JUSTIFY, iX, iY, self.Z_CONTROLS, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_GENERAL, -1, -1)
			screen.setHitTest(sTempName, HitTestTypes.HITTEST_NOHIT)

	def getTotalCommerceValue(self):
		iTotal = 0
		for iYield in range(YieldTypes.YIELD_HAMMERS):
			iTotal += gc.getActivePlayer().countTotalYieldStored(iYield) * gc.getActivePlayer().getYieldSellPrice(iYield)
		return iTotal

	def getTotalYieldBoughtValue(self):
		iTotal = 0
		for iYield in range(YieldTypes.YIELD_HAMMERS):
			iTotal += gc.getPlayer(gc.getActivePlayer().getParent()).getYieldBoughtTotal(iYield)
		return iTotal

	def getTotalImprovementCostValue(self):
		iTotal = 0
		dBuildInfos = {}
		for iBuildInfo in range(gc.getNumBuildInfos()):
			pBuildInfo = gc.getBuildInfo(iBuildInfo)
			iImprovementType = pBuildInfo.getImprovement()
			if (iImprovementType != -1):
				dBuildInfos[iImprovementType] = iBuildInfo

		for iPlot in range(oMap.numPlots()):
			pPlot = oMap.plotByIndex(iPlot)
			if (pPlot.getImprovementType() != -1) and (pPlot.getImprovementType() in dBuildInfos.keys()) and (pPlot.getOwner() == gc.getGame().getActivePlayer()):
				#This is the segment that will run the seperate code if the Dll is not present.
				try:
					iTotal += gc.getActivePlayer().getBuildCost(pPlot,dBuildInfos[pPlot.getImprovementType()])
				except:
					iTotal += gc.getBuildInfo(dBuildInfos[pPlot.getImprovementType()]).getCost()
		return iTotal

	#############################################################################################################

	def showHeader(self):
		screen = self.getScreen()
		iX = 0
		iY = 0
		screen.addDDSGFC(self.HEADER_PANEL_ID, ArtFileMgr.getInterfaceArtInfo("INTERFACE_SCREEN_TITLE").getPath(), self.X_SCREEN, self.Y_SCREEN, self.W_SCREEN, self.H_BAR, WidgetTypes.WIDGET_GENERAL, -1, -1)

		sTitle = self.getText("TXT_KEY_FINANCIAL_ADVISOR_TITLE")
		screen.setText(self.HEADER_ID, self.BACKGROUND_ID, sTitle, CvUtil.FONT_CENTER_JUSTIFY, self.W_SCREEN / 2, self.Y_SCREEN + 2, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_GENERAL, -1, -1)

		return None

	def showFooter(self):
		screen = self.getScreen()
		iX = 0
		iY = 0
		screen.addPanel(self.FOOTER_PANEL_ID, u"", u"", True, False, iX, self.H_SCREEN - self.H_BAR, self.W_SCREEN, self.H_BAR, PanelStyles.PANEL_STYLE_BOTTOMBAR, WidgetTypes.WIDGET_GENERAL, -1, -1)
		screen.setText(self.EXIT_ID, self.BACKGROUND_ID, u"<font=4>EXIT</font>", CvUtil.FONT_RIGHT_JUSTIFY, self.W_SCREEN - 30, self.H_SCREEN - 40, self.Z_CONTROLS, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_CLOSE_SCREEN, -1, -1)

		screen.setFocus(self.EXIT_ID)
		return None

	#############################################################################################################

	def getText(self, sText, tArgs = (), iColor = -2):
		if (type(sText) != str) and (type(sText) != unicode):
			sText = str(sText)
		try:
			sText = oLocalText.getText(sText, tArgs)
		except:
			pass
		if (iColor == -2):
			iColor = gc.getInfoTypeForString("COLOR_FONT_CREAM")
		sText = oLocalText.changeTextColor(sText, iColor)
		return sText

	#############################################################################################################

