# Sid Meier's Civilization 4
# Copyright Firaxis Games 2005
import os
from CvPythonExtensions import (CyGlobalContext, CyArtFileMgr, CyTranslator,
																FontTypes, WidgetTypes, PanelStyles,
																CyGameTextMgr, GenericButtonSizes,
																CivilopediaPageTypes, CommerceTypes,
																isTechRequiredForUnit,
																isTechRequiredForBuilding,
																isTechRequiredForProject)
import CvUtil
import CvPediaScreen
# import ScreenInput
import CvScreenEnums

# globals
gc = CyGlobalContext()
ArtFileMgr = CyArtFileMgr()
localText = CyTranslator()
PAEMod = "Pie'sAncientEurope"

class CvPediaTech(CvPediaScreen.CvPediaScreen):
		"Civilopedia Screen for Techs"

		def __init__(self, main):
				self.iTech = -1
				self.top = main

				self.X_TECH_PANE = 10
				self.Y_TECH_PANE = 55
				self.W_TECH_PANE = 355
				self.H_TECH_PANE = 110

				self.X_ICON = 40
				self.Y_ICON = 60
				self.W_ICON = 100
				self.H_ICON = 100
				self.ICON_SIZE = 64

				self.X_COST = 150
				self.Y_COST = 90

				self.BUTTON_SIZE = 64

				self.X_PREREQ_PANE = 10
				self.Y_PREREQ_PANE = 167
				self.W_PREREQ_PANE = 355
				self.H_PREREQ_PANE = 100

				self.X_LEADS_TO_PANE = 10
				self.Y_LEADS_TO_PANE = 269
				self.W_LEADS_TO_PANE = 355
				self.H_LEADS_TO_PANE = 110

				self.X_UNIT_PANE = 10
				self.Y_UNIT_PANE = 381
				self.W_UNIT_PANE = 355
				self.H_UNIT_PANE = 110

				self.X_BUILDING_PANE = 10
				self.Y_BUILDING_PANE = 493
				self.W_BUILDING_PANE = 355
				self.H_BUILDING_PANE = 110

				self.X_CIV_PANE = 10
				self.Y_CIV_PANE = 605
				self.W_CIV_PANE = 355
				self.H_CIV_PANE = 110

				self.X_SPECIAL_PANE = 375
				self.Y_SPECIAL_PANE = 55
				self.W_SPECIAL_PANE = 415
				self.H_SPECIAL_PANE = 200

				self.X_QUOTE_PANE = 375
				self.Y_QUOTE_PANE = 260
				self.W_QUOTE_PANE = 415
				self.H_QUOTE_PANE = 450

		def interfaceScreen(self, iTech):

				self.iTech = iTech

				self.top.deleteAllWidgets()

				screen = self.top.getScreen()

				bNotActive = (not screen.isActive())
				if bNotActive:  # or self.top.iLastScreen != CvScreenEnums.PEDIA_TECH:  # PAE different Link menu height
						self.top.setPediaCommonWidgets()

				# Header...
				szHeader = u"<font=4b>" + gc.getTechInfo(self.iTech).getDescription().upper() + u"</font>"
				screen.setLabel(self.top.getNextWidgetName(), "Background", szHeader, CvUtil.FONT_CENTER_JUSTIFY, self.top.X_SCREEN, self.top.Y_TITLE,
												0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_GENERAL, CivilopediaPageTypes.CIVILOPEDIA_PAGE_TECH, iTech)

				# Top
				screen.setText(self.top.getNextWidgetName(), "Background", self.top.MENU_TEXT, CvUtil.FONT_LEFT_JUSTIFY, self.top.X_MENU,
											 self.top.Y_MENU, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_PEDIA_MAIN, CivilopediaPageTypes.CIVILOPEDIA_PAGE_TECH, -1)

				if self.top.iLastScreen != CvScreenEnums.PEDIA_TECH or bNotActive:
						self.placeLinks(True)
						self.top.iLastScreen = CvScreenEnums.PEDIA_TECH
				else:
						self.placeLinks(False)

				screen.addPanel(self.top.getNextWidgetName(), "", "", False, False, self.X_TECH_PANE, self.Y_TECH_PANE, self.W_TECH_PANE, self.H_TECH_PANE, PanelStyles.PANEL_STYLE_BLUE50)

				# Icon
				screen.addPanel(self.top.getNextWidgetName(), "", "", False, False, self.X_ICON, self.Y_ICON, self.W_ICON, self.H_ICON, PanelStyles.PANEL_STYLE_MAIN)
				screen.addDDSGFC(self.top.getNextWidgetName(), gc.getTechInfo(self.iTech).getButton(), self.X_ICON + self.W_ICON/2 - self.ICON_SIZE /
												 2, self.Y_ICON + self.H_ICON/2 - self.ICON_SIZE/2, self.ICON_SIZE, self.ICON_SIZE, WidgetTypes.WIDGET_GENERAL, -1, -1)

				# Kosten
				szCostId = self.top.getNextWidgetName()
				if self.top.iActivePlayer == -1:
						szCostText = localText.getText("TXT_KEY_PEDIA_COST", (gc.getTechInfo(iTech).getResearchCost(), )) + u"%c" % (gc.getCommerceInfo(CommerceTypes.COMMERCE_RESEARCH).getChar())
				else:
						szCostText = localText.getText("TXT_KEY_PEDIA_COST", (gc.getTeam(gc.getGame().getActiveTeam()).getResearchCost(iTech), )) + \
								u"%c" % (gc.getCommerceInfo(CommerceTypes.COMMERCE_RESEARCH).getChar())
				screen.setLabel(szCostId, "Background", u"<font=4>" + szCostText.upper() + u"</font>", CvUtil.FONT_LEFT_JUSTIFY,
												self.X_COST + 25, self.Y_COST, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_GENERAL, -1, -1)

				# Zeitalter (PAE)
				screen.setLabel(self.top.getNextWidgetName(), "Background", u"<font=4>" + gc.getEraInfo(gc.getTechInfo(self.iTech).getEra()).getDescription() +
												u"</font>", CvUtil.FONT_LEFT_JUSTIFY, self.X_COST + 25, self.Y_COST + 25, 0, FontTypes.TITLE_FONT, WidgetTypes.WIDGET_GENERAL, -1, -1)

				# Place Required techs
				self.placePrereqs()

				# Place Allowing techs
				self.placeLeadsTo()

				# Place Units
				self.placeUnits()

				# Place buildings
				self.placeBuildings()

				# Place Civs: Anzeige nur(!) bei disabled Techs (PAE)
				if not gc.getTechInfo(iTech).isDisable():
						lCivs = self.getTechOfCivs()
						if len(lCivs) > 0:
								self.placeCivs(lCivs)

				# Place the Special abilities block
				self.placeSpecial()

				# Place the quote for this technology
				self.placeQuote()

		# Place prereqs...

		def placeLeadsTo(self):

				screen = self.top.getScreen()

				# add pane and text
				szLeadsTo = localText.getText("TXT_KEY_PEDIA_LEADS_TO", ())

				panelName = self.top.getNextWidgetName()
				screen.addPanel(panelName, szLeadsTo, "", False, True, self.X_LEADS_TO_PANE, self.Y_LEADS_TO_PANE, self.W_LEADS_TO_PANE, self.H_LEADS_TO_PANE, PanelStyles.PANEL_STYLE_BLUE50)

				screen.attachLabel(panelName, "", "  ")

				for j in range(gc.getNumTechInfos()):
						for k in range(gc.getNUM_OR_TECH_PREREQS()):
								iPrereq = gc.getTechInfo(j).getPrereqOrTechs(k)
								if (iPrereq == self.iTech):
										screen.attachImageButton(panelName, "", gc.getTechInfo(j).getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_DERIVED_TECH, j, self.iTech, False)
						for k in range(gc.getNUM_AND_TECH_PREREQS()):
								iPrereq = gc.getTechInfo(j).getPrereqAndTechs(k)
								if (iPrereq == self.iTech):
										screen.attachImageButton(panelName, "", gc.getTechInfo(j).getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_DERIVED_TECH, j, self.iTech, False)

		# Place prereqs...
		def placePrereqs(self):

				screen = self.top.getScreen()

				szRequires = localText.getText("TXT_KEY_PEDIA_REQUIRES", ())

				panelName = self.top.getNextWidgetName()
				screen.addPanel(panelName, szRequires, "", False, True, self.X_PREREQ_PANE, self.Y_PREREQ_PANE, self.W_PREREQ_PANE, self.H_PREREQ_PANE, PanelStyles.PANEL_STYLE_BLUE50)

				screen.attachLabel(panelName, "", "  ")

				bFirst = True
				for j in range(gc.getNUM_AND_TECH_PREREQS()):
						eTech = gc.getTechInfo(self.iTech).getPrereqAndTechs(j)
						if (eTech > -1):
								if (not bFirst):
										screen.attachLabel(panelName, "", localText.getText("TXT_KEY_AND", ()))
								else:
										bFirst = False
								screen.attachImageButton(panelName, "", gc.getTechInfo(eTech).getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_REQUIRED_TECH, eTech, j, False)

				# count the number of OR techs
				nOrTechs = 0
				for j in range(gc.getNUM_OR_TECH_PREREQS()):
						if (gc.getTechInfo(self.iTech).getPrereqOrTechs(j) > -1):
								nOrTechs += 1

				szLeftDelimeter = ""
				szRightDelimeter = ""
				#  Display a bracket if we have more than one OR tech and at least one AND tech
				if (not bFirst):
						if (nOrTechs > 1):
								szLeftDelimeter = localText.getText("TXT_KEY_AND", ()) + "( "
								szRightDelimeter = " ) "
						elif (nOrTechs > 0):
								szLeftDelimeter = localText.getText("TXT_KEY_AND", ())
						else:
								return

				if len(szLeftDelimeter) > 0:
						screen.attachLabel(panelName, "", szLeftDelimeter)

				bFirst = True
				for j in range(gc.getNUM_OR_TECH_PREREQS()):
						eTech = gc.getTechInfo(self.iTech).getPrereqOrTechs(j)
						if (eTech > -1):
								if (not bFirst):
										screen.attachLabel(panelName, "", localText.getText("TXT_KEY_OR", ()))
								else:
										bFirst = False
								screen.attachImageButton(panelName, "", gc.getTechInfo(eTech).getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_REQUIRED_TECH, eTech, j, False)

				if len(szRightDelimeter) > 0:
						screen.attachLabel(panelName, "", szRightDelimeter)

		# Place units...

		def placeUnits(self):

				screen = self.top.getScreen()
				panelName = self.top.getNextWidgetName()
				screen.addPanel(panelName, localText.getText("TXT_KEY_PEDIA_UNITS_ENABLED", ()), "", False, True, self.X_UNIT_PANE,
												self.Y_UNIT_PANE, self.W_UNIT_PANE, self.H_UNIT_PANE, PanelStyles.PANEL_STYLE_BLUE50)

				screen.attachLabel(panelName, "", "  ")

				for eLoopUnit in range(gc.getNumUnitInfos()):
						if (eLoopUnit != -1):
								if (isTechRequiredForUnit(self.iTech, eLoopUnit)):
										szButton = gc.getUnitInfo(eLoopUnit).getButton()
										if self.top.iActivePlayer != -1:
												szButton = gc.getPlayer(self.top.iActivePlayer).getUnitButton(eLoopUnit)
										screen.attachImageButton(panelName, "", szButton, GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_UNIT, eLoopUnit, 1, False)

		# Place buildings...
		def placeBuildings(self):

				screen = self.top.getScreen()

				panelName = self.top.getNextWidgetName()
				screen.addPanel(panelName, localText.getText("TXT_KEY_PEDIA_BUILDINGS_ENABLED", ()), "", False, True, self.X_BUILDING_PANE,
												self.Y_BUILDING_PANE, self.W_BUILDING_PANE, self.H_BUILDING_PANE, PanelStyles.PANEL_STYLE_BLUE50)

				screen.attachLabel(panelName, "", "  ")

				for eLoopBuilding in range(gc.getNumBuildingInfos()):
						if (eLoopBuilding != -1):
								if (isTechRequiredForBuilding(self.iTech, eLoopBuilding)):
										screen.attachImageButton(panelName, "", gc.getBuildingInfo(eLoopBuilding).getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM,
																						 WidgetTypes.WIDGET_PEDIA_JUMP_TO_BUILDING, eLoopBuilding, 1, False)

				for eLoopProject in range(gc.getNumProjectInfos()):
						if (isTechRequiredForProject(self.iTech, eLoopProject)):
								screen.attachImageButton(panelName, "", gc.getProjectInfo(eLoopProject).getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM,
																				 WidgetTypes.WIDGET_PEDIA_JUMP_TO_PROJECT, eLoopProject, 1, False)

		# Place CIVs who are able to research this technology (PAE)
		def placeCivs(self, lCivs):

				screen = self.top.getScreen()

				panelName = self.top.getNextWidgetName()
				screen.addPanel(panelName, localText.getText("TXT_KEY_PEDIA_CIVS_ENABLED", ()), "", False, True, self.X_CIV_PANE,
												self.Y_CIV_PANE, self.W_CIV_PANE, self.H_CIV_PANE, PanelStyles.PANEL_STYLE_BLUE50)

				screen.attachLabel(panelName, "", "  ")

				# Civs anzeigen
				for item in lCivs:
						screen.attachImageButton(panelName, "", gc.getCivilizationInfo(item).getButton(), GenericButtonSizes.BUTTON_SIZE_CUSTOM, WidgetTypes.WIDGET_PEDIA_JUMP_TO_CIV, item, 1, False)

		# Effects
		def placeSpecial(self):

				screen = self.top.getScreen()

				panelName = self.top.getNextWidgetName()
				screen.addPanel(panelName, "", "", True, False, self.X_SPECIAL_PANE, self.Y_SPECIAL_PANE, self.W_SPECIAL_PANE, self.H_SPECIAL_PANE, PanelStyles.PANEL_STYLE_BLUE50)

				listName = self.top.getNextWidgetName()

				szSpecialText = CyGameTextMgr().getTechHelp(self.iTech, True, False, False, False, -1)[1:]

				# Obsolete Unit
				if self.iTech == gc.getInfoTypeForString("TECH_GRENZHEER"):
						if szSpecialText != "":
								szSpecialText += "\n"
						szSpecialText += CyTranslator().getText("TXT_KEY_TECH_OBSOLETES", (gc.getUnitInfo(gc.getInfoTypeForString("UNIT_PRAETORIAN")).getDescription(),))

				# Spionagemissionen (werden erst im Spiel angezeigt, da Spionage auch ausgeschaltet sein kann -> getNumEspionageMissionInfos() = 0)
				for eLoopEspionage in range(gc.getNumEspionageMissionInfos()):
						if gc.getEspionageMissionInfo(eLoopEspionage).getTechPrereq() == self.iTech:
								if szSpecialText != "":
										szSpecialText += "\n"
								szSpecialText += CyTranslator().getText("TXT_KEY_MESSAGE_TECH_ESPIONAGE_MISSIONS", (gc.getEspionageMissionInfo(eLoopEspionage).getDescription(),))

				# PAE - Tradeable/conquerable
				if szSpecialText != "":
						szSpecialText += "\n"
				if gc.getTechInfo(self.iTech).isTrade():
						szSpecialText += CyTranslator().getText("TXT_KEY_MESSAGE_TECH_TRADEABLE", ())
				else:
						szSpecialText += CyTranslator().getText("TXT_KEY_MESSAGE_TECH_NOT_TRADEABLE", ())

				# BTS: Auflistung
				screen.addMultilineText(listName, szSpecialText, self.X_SPECIAL_PANE+5, self.Y_SPECIAL_PANE+20, self.W_SPECIAL_PANE -
																30, self.H_SPECIAL_PANE-10, WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)

		# Pedia text
		def placeQuote(self):
				screen = self.top.getScreen()

				panelName = self.top.getNextWidgetName()
				screen.addPanel(panelName, "", "", True, True,
												self.X_QUOTE_PANE, self.Y_QUOTE_PANE, self.W_QUOTE_PANE, self.H_QUOTE_PANE, PanelStyles.PANEL_STYLE_BLUE50)

				szQuote = gc.getTechInfo(self.iTech).getQuote()
				if len(gc.getTechInfo(self.iTech).getStrategy()) > 0:
						szQuote += u"\n\n"
						szQuote += localText.getText("TXT_KEY_CIVILOPEDIA_STRATEGY", ())
						szQuote += gc.getTechInfo(self.iTech).getStrategy()
				szQuote += u"\n\n"
				szQuote += localText.getText("TXT_KEY_CIVILOPEDIA_BACKGROUND", ())
				szQuote += gc.getTechInfo(self.iTech).getCivilopedia()

				szQuoteTextWidget = self.top.getNextWidgetName()
				screen.addMultilineText(szQuoteTextWidget, szQuote, self.X_QUOTE_PANE + 10, self.Y_QUOTE_PANE + 10,
																self.W_QUOTE_PANE - 10, self.H_QUOTE_PANE - 15, WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_LEFT_JUSTIFY)

		def placeLinks(self, bRedraw):

				screen = self.top.getScreen()

				if bRedraw:
						screen.clearListBoxGFC(self.top.LIST_ID)

				techsList = self.getSortedList(gc.getNumTechInfos(), gc.getTechInfo)

				iSelected = 0
				i = 0
				A = ""
				for iI in range(gc.getNumTechInfos()):
						# PAE: and not isDisable
						if not gc.getTechInfo(techsList[iI][1]).isGraphicalOnly() and not gc.getTechInfo(techsList[iI][1]).isDisable():

								# Buchstabe
								B = techsList[iI][0][:1]
								if A == "" or A != B and not B.isdigit():
										A = B
										i += 1  # Zeile in der linken Navi
										# Buchstabe anzeigen
										if bRedraw:
												screen.appendListBoxStringNoUpdate(self.top.LIST_ID, u"<font=2>[" + A + u"]</font>", WidgetTypes.WIDGET_GENERAL, -1, -1, CvUtil.FONT_CENTER_JUSTIFY)

								# Name anzeigen
								if bRedraw:
										screen.appendListBoxStringNoUpdate(self.top.LIST_ID, techsList[iI][0], WidgetTypes.WIDGET_PEDIA_JUMP_TO_TECH, techsList[iI][1], 0, CvUtil.FONT_LEFT_JUSTIFY)
								if techsList[iI][1] == self.iTech:
										iSelected = i
								i += 1

				if bRedraw:
						screen.updateListBox(self.top.LIST_ID)

				screen.setSelectedListBoxStringGFC(self.top.LIST_ID, iSelected)

		# Will handle the input for this screen...
		def handleInput(self, inputClass):
				return 0

		# Civs that can research disabled Techs (PAE)
		# Repaired by Dertuek, thx!
		def getTechOfCivs(self):
				lCivs = []
				"""
				bRead = False

				# Tech vorerst allen Civs zuweisen
				iNumCivs = gc.getNumCivilizationInfos()
				for i in range(iNumCivs): lCivs.append(i)

				# Datei auslesen und bei disable Tech Civ aus der Liste droppen
				datei = open(os.path.join("Mods", PAEMod, "Assets", "XML","Civilizations","CIV4CivilizationInfos.xml"))
				for zeile in datei:
					if "<CivilizationInfo>" in zeile: bRead = False
					if "<Type>CIVILIZATION" in zeile: sCiv = zeile[zeile.find(">")+1:zeile.find("</")]
					if "<DisableTechs>" in zeile: bRead = True
					if bRead:
						if "<TechType>" in zeile:
							sTech = zeile[zeile.find(">")+1:zeile.find("</")]
							iTech = gc.getInfoTypeForString(sTech)
							iCiv = gc.getInfoTypeForString(sCiv)
							if iTech == self.iTech and iCiv in lCivs: lCivs.remove(iCiv)
				datei.close()

				if len(lCivs) == iNumCivs: lCivs = []
				else: lCivs.remove(gc.getInfoTypeForString("CIVILIZATION_MINOR"))

				return lCivs
				"""

				# Tech vorerst allen Civs zuweisen
				iNumCivs = gc.getNumCivilizationInfos()
				for i in range(iNumCivs):
						if not gc.getCivilizationInfo(i).isCivilizationDisableTechs(self.iTech) and i != gc.getInfoTypeForString("CIVILIZATION_MINOR"):
								lCivs.append(i)

				if len(lCivs) == iNumCivs - 1:
						lCivs = []

				return lCivs
