' streets

' map screen
' lepsza pauza
' lepszy font w title
' ingame menu polish


Strict

Import Wiering.BMFont
'Import pantson.theora
Import odd.aspect

?Win32
Import "-ladvapi32"
Import "src/fullaccess.cpp"
Import "src/gabcab.o"
'Import "src/gabcab2.o"
?

Include "src/common/MaxModMac.bmx"
Include "src/common/soundManager.bmx"
Include "src/common/options.bmx"



Global verNumber:String = "v. 1.03"
Global bDir:String = getBundleResourceUrl("")

SeedRnd MilliSecs()

Include "src/common.bmx"
Include "src/branding.bmx"
Include "src/klienci.bmx"
Include "src/miasto.bmx"
Include "src/obiekty.bmx"
Include "src/szukanieTrasy.bmx"
Include "src/tsconfig2.bmx"
Include "src/ulice.bmx"
Include "src/specialFolders.bmx"
Include "src/taksowki.bmx"
Include "src/hud.bmx"
Include "src/captions.bmx"
Include "src/strzala.bmx"
Include "src/mapa.bmx"
Include "src/level_sequencer.bmx"
Include "src/tips.bmx"
Include "src/upgradeShop.bmx"
Include "src/menu.bmx"
Include "src/titleScreen.bmx"
Include "src/mapScreen.bmx"
Include "src/profiles.bmx"
Include "src/awards.bmx"
Include "src/credits.bmx"
Include "src/credits2.bmx"
Include "src/optionsScreen.bmx"
Include "src/autorouting.bmx"
Include "src/uliceKrzywe.bmx"
Include "src/assistants.bmx"

Include "src/helpTips.bmx"
Include "src/yesOrNo.bmx"
Include "src/powerUps.bmx"
Include "src/inGameOptions.bmx"

Include "src/common/colors.bmx"
Include "src/common/deltatime.bmx"
Include "src/common/mouse.bmx"
Include "src/common/string.bmx"
Include "src/common/zBuffer.bmx"
Include "src/common/sparksEngine3.bmx"
Include "src/gui/gui-includer.bmx"
Include "src/comboParticle.bmx"
Include "src/emitter.bmx"
Include "src/giveAward.bmx"
Include "src/pogoda.bmx"
Include "src/playLog.bmx"
Include "src/savePlaylog.bmx"
Include "src/heli.bmx"
Include "src/stats.bmx"
Include "src/http_post.bmx"
Include "src/sprAwards.bmx"
Include "src/tipsPanel.bmx"
Include "src/loading.bmx"
Include "src/logo.bmx"
Include "src/fulling-help.bmx"
Include "src/ekran.bmx"

AppTitle = "GabCab "+verNumber

GCSetMode( 1 )

Print "BDIR : "+bDir
Global delta#
Global deltatime:TDeltaTime = TDeltaTime.Create(60)
Global miasto:TMiasto = New TMiasto
Global taxiManager:TTaxiManager = New TTaxiManager
Global ulice:TUlice = New TUlice
Global klienci:TKlienci = New TKlienci
Global managerObiektow:TManagerObiektow = New TManagerObiektow
Global mouse:TMouse = New TMouse
Global captions:TCaptionManager = New TCaptionManager
Global score# = 0
Global scale# = 1.00, cabScale# = 0.85
Global hud:THUD = New THUD
Global mapa:TMapa = New TMapa
Global paths:TPaths = New TPaths
'Global wybierzTrase:TWybierzTrase = New TWybierzTrase
Global zBuffer:TZBuffer = New TZBuffer
Global levels:TLevelSequencer = New TLevelSequencer
Global tips:TTips = New TTips
Global upgrades:TUpgradeManager = New TUpgradeManager
Global ingameMenu:TINGAMEMENU = New TInGameMenu
Global title:TTitleScreen = New TTitleScreen
Global mapScreen:TMapScreen = New TMapScreen
Global profiles:TProfiles = New TProfiles
Global awards:TAwards = New TAwards
Global options:TOptions = New TOptions
Global credits:TCreditsScreen = New TCreditsScreen
Global optionsScreen:TOptionsScreen = New TOptionsScreen
Global inGameOptions:TInGameOptions = New TInGameOptions
Global autorouter:TAutorouter = New TAutorouter
Global streetLoader:TStreetLoader = New TStreetLoader
Global streetPaths:TStreetPaths = New TStreetPaths
Global streetPathsASS:TStreetPathsASS = New TStreetPathsASS
Global stageScore:TStageScore = New TStageScore
Global helpTips:THelpTips = New THelpTips
Global yesOrNo:TYesOrNo = New TYesOrNo
Global assManager:TAssManager = New TAssManager
Global roadPosition:TRoadPosition = New TRoadPosition
Global dajAward:TDajAward = New TDajAward
Global heliManager:THeliManager = New THeliManager
Global stats:TStats = New TStats
Global tipsPanel:TTipsPanel = New TTipsPanel
Global fullingHelp:THelpBox = New THelpBox
Global loadingScreen:TLoadingScreen = New TLoadingScreen
Global mappopUp:TMapPopUp = New TMapPopUp
Global credits2:TCreditsScreen2 = New TCreditsScreen2
Global focusFont:TBMFont

Global full
Global cheatsOn = False

If FileType("cheats.txt") Then cheatsOn = True

GetDataFolders()

OnEnd stopProgram

options.Load()
optionsScreen.openScreen()


levels.wczytajUstawienia()
managerObiektow.wgrajDefinicjeObiektow()
awards.setup()
profiles.wczytajListe()

?win32
SetIcon(AppFile, GetActiveWindow())
?

centerWindow()
branding.setup()	
branding.mainLoop()
loadingScreen.setup()
Logo_go()
loadingScreen.fadeMeUp()
loadingScreen.draw()

SetBlend ALPHABLEND


mouse.loadCursor(0,  bdir + "gfx/gui/mouse.png", 4, 4)
mouse.loadCursor(1,  bdir + "gfx/refueling.png", 3, 1)
mouse.loadOutline(0,  bdir + "gfx/gui/mouse_outline.png", 4, 4)
mouse.propaganda = LoadImage( bdir + "gfx/mouse_propaganda.png")
mouse.hotSpot = LoadImage( bdir + "gfx/mouse_hotSpot.png")

MidHandleImage mouse.propaganda
MidHandleImage mouse.hotSpot

mouse.magnet = LoadImage( bdir + "gfx/gui/magnetMouse.png")

SetImageHandle mouse.magnet, 4, 4

loadingScreen.draw()
credits.setup()

optionsScreen.wgrajGfx()
inGameOptions.wgrajGfx()
loadingScreen.draw()

klienci.wgrajDefinicje()
upgrades.setup()
loadingScreen.draw()
zBuffer.setup(15)
TCabDef.loadDefs()
taxiManager.wczytajGfx()
loadingScreen.draw()
miasto.wgrajGfx()
paths.wgrajGfx()
klienci.wgrajObrazki()
captions.wgrajGfx()
loadingScreen.draw()
tips.wgrajGfx()
hud.wgrajGfx()
stageScore.setup()
helpTips.setup()
loadingScreen.draw()
yesOrNo.setup()
assManager.setupManager()
loadingScreen.draw()
setupPogoda()
heliManager.setup()
stats.setup()
dajAward.setup()
tipsPanel.setup()
loadingScreen.draw()
mapPopUp.setup()
mapScreen.setup()
credits2.setup()
fullingHelp.setup()
songManager.LoadSong( bdir + "sfx/menu.ogg")
songManager.LoadSong( bdir + "sfx/gabcap-gplay2b.ogg")
songManager.LoadSong( bdir + "sfx/gabcap-gplay2b-end.ogg", False)

loadComboParticle()
loadingScreen.draw()
ingameMenu.wgrajGfx()
loadSparkImage(0,  bdir + "gfx/particle-1.png")
loadSparkImage(1,  bdir + "gfx/particle-2.png")
loadSparkImage(2,  bdir + "gfx/particles/nutka.png")

title.wgrajGfx()
optionsScreen.wgrajGUI(title.res)
inGameOptions.wgrajGUI(miasto.resources)
loadingScreen.draw()
profiles.wczytajGUI()
loadingScreen.draw()
globalSnd.setup()
focusFont = TBMFont.Create( bdir + "gfx/fonts/", "whitesmall_22.fnt" )
focusFont.align = ALIGN_CENTER
Global  _txtHello:String = readTxtData( loadTxtFile( bdir + "data/texts.txt"), 487 )
HideMouse()
loadingScreen.draw()

songManager.setplayed( bdir + "sfx/menu.ogg", 0)
title.flash = MilliSecs()
loadingScreen.fadeMeDown()

Local wynikTitle = 0
AddHook FlipHook, focusCheck


title.reset()
FlushKeys()
FlushMouse()

Repeat
	deltatime.update()
	delta = deltatime.currDelta()
	
	If songManager._played[0].NotPLaying() Or songManager._played[0].name <>  bdir + "sfx/menu.ogg" Then songManager.setplayed("sfx/menu.ogg", 0)

	
	mouse.fetchState()
	
	title.update()
	title.form.update()
	title.rysuj()
	
	
	mouse.draw()
	If Not profiles.wybrany Then profiles.pokazNew()
	title.helloLabel.text = _txtHello+" "+profiles.wybrany.nazwa
	title.helloLabel.a = 0.5
'	If title.form.xo = 0 Then
		If title.form.Button("1").click Then 
			wynikTitle = 1
			title.dFade = 1
		EndIf
	
		If title.form.Button("2").click Then 
			profiles.pokaz()
			title.slideIn = 90
		EndIf
		
		If title.form.Button("3").click Then optionsScreen.pokaz()
		
		If title.form.Button("4").click Then credits2.pokaz()
	
		If title.form.Button("5").click Then endProgram()
	'End If
	Flip
	AspectCls()		
		
	'If KeyHit(KEY_C) Then credits.mainLoop()
	
	If title.fade = 1 And title.dFade = 1 Then
		If wynikTitle = 1 Then
			songManager.stopChn(0)
			Local w = mapScreen.mainLoop()
			'DebugStop
			If w Then 
				letsPlay()
				
			Else
			
			End If
			wynikTitle = 0
			title.dFade = 0
		End If
	
	End If
	
Forever


Function stopProgram()
	songManager.pauseChannels();
	saveLog()
End Function

Function endProgram()
	'DebugStop
	stopProgram()
	options.save()
	End 
End Function

Function drawGame2()
	DrawImage mapa.bgImg, 0, 0
	miasto.rysujDekoryZwykle()
	mapa.rysujUlice() 
	taxiManager.rysujLinieDoCelow()
	streetPaths.drawAll()
	miasto.rysujObiekty()
	drawPogoda()
	klienci.rysujWszystkich()
	taxiManager.rysujWszystkie()
	hud.rysuj()
	captions.drawAll()
	tips.rysujWszystkie()
	assManager.draw()
	drawComboParticles()
	heliManager.drawPackages()
	zBuffer.sortAllLayers()
	zBuffer.drawAllLayers()
	
	heliManager.draw()
	fullingHelp.draw()
	
	_updateEmitters()
	hud.rysujCele()
	hud.rysujPorade()

End Function

Function drawGame()
	Local w = miasto.updateAll()
	
		DrawImage mapa.bgImg, 0, 0
		miasto.rysujDekoryZwykle()
		mapa.rysujUlice() 
		updateComboParticles()
		taxiManager.rysujLinieDoCelow()
		streetPaths.drawAll()
		miasto.rysujObiekty()
		drawPogoda()
		klienci.rysujWszystkich()
		taxiManager.rysujWszystkie()
		hud.rysuj()
		captions.drawAll()
		tips.rysujWszystkie()
		assManager.draw()
		drawComboParticles()
		heliManager.drawPackages()
		zBuffer.sortAllLayers()
		zBuffer.drawAllLayers()
		
		heliManager.draw()
		fullingHelp.draw()
		
		_updateEmitters()
		hud.rysujCele()
		hud.rysujPorade()
		
		SetColor 255, 0, 255
		SetScale 1,1
		SetAlpha 1
		SetBlend ALPHABLEND
		SetRotation 0		
		SetColor 255, 255, 255
		
		
		
	Return w
End Function


Function prepareLetsPlay()
	'DebugStop
	levels.wgraj()
	'DebugStop
	upgrades.mainLoop()
	miasto.stanGry = 2
	taxiManager.wybranaTaxowa.fuel = upgrades.getTankCapacity()
	songManager.setplayed("sfx/"+miasto.musicFile, 0)
	globalSnd.play_silnik()	
End Function

Function letsPlay()

	Local fade:Float = 0
	Local wynik = 0
	Local dFade:Float = 0
	Local dc = True, dl = False
	Local cabOY = 0, cabOX = 0
	Local gcTime = MilliSecs() + 1000
		
	prepareLetsPlay()
	
	Repeat
		deltatime.update()
		delta = deltatime.currDelta()
		mouse.licznik = 0
		mouse.fetchState()	
		
		If MilliSecs() > gcTime Then 
			gcTime = MilliSecs() + 1000
			
		End If
		Rem
		If fade < dFade Then
			fade:+2'*delta
			If fade > dFade Then fade = dFade
		End If
		If fade > dFade Then
			fade:-2'*delta
			If fade < dFade Then fade = dFade
		End If
		End Rem
		fade = dFade
		Local ddd = drawGame()
		
		Select ddd
			Case -1; dFade = 1; wynik = -1; globalsnd.stopMagicMusic(); Return
			Case -2; dFade = 1; wynik = -2
			Case -3; dFade = 1; fade = 1; mapScreen.fade = 0; mapScreen.dFade = 0;
		End Select
		
		If fade = 1 And dFade = 1 Then
			Select wynik
				Case -1; Return
				Case -2
					songManager.stopChn(0)
					profiles.wybrany.aktualnyStage = mapScreen.aktualnyStage.id
					profiles.wybrany.aktualnyLevel = mapScreen.aktualnyLevel
					globalsnd.stopMagicMusic()
					
					Local w = mapScreen.mainLoop()
					
					If w Then 
						prepareletsPlay()
						fade = 1
						dFade = 0
					Else
						Return
					End If
				Case -3	
					globalsnd.stopMagicMusic()
					Local w = mapScreen.mainLoop()
					
					If w Then 
						prepareletsPlay()
						fade = 1
						dFade = 0
					Else
						Return
					End If

			End Select
		End If
		If hud.czyRysowacLevelSummary And (Not tips.lista.count()) Then 
			hud.rysujPodsumowanieLevelu()

	
		EndIf
		
		If miasto.stanGry = 4 Or (inGameMenu.outro) Then
			If TPowerUp.propagandaPick Or TPowerUp.hotspotPick Then 
				TPowerUp.getBack()
			End If
			miasto.rysujMenu()
		EndIf
		
		fullingHelp.update()
		If cheatsOn Then
			If KeyHit(KEY_F1) Then levels.wgraj(); 
			If KeyHit(KEY_L) Then taxiManager.wybranataxowa.fuel = 0
			If KeyHit(KEY_M) Then hud.startSummary()
			If KeyHit(KEY_SPACE) Then dc = Not dc
			If KeyHit(KEY_D) Then hud.dodajPunkty(400)
			If KeyHit(KEY_T) Then 
				hud.czasGry = hud.czas; 
				For Local o:TObiekt = EachIn mapa.listaObiektow
					o.klienci = CreateList()
				Next
				hud.customersTotal = 10
			End If
			If KeyHit(KEY_C) Then taxiManager.wybranaTaxowa.combo:+1
			
			If KeyHit(KEY_NUM1) Then assManager.ustawAsystenta(0)
			If KeyHit(KEY_NUM2) Then assManager.ustawAsystenta(1)
			If KeyHit(KEY_NUM3) Then assManager.ustawAsystenta(2)
			If KeyHit(KEY_NUM4) Then assManager.ustawAsystenta(3)
			If KeyHit(KEY_V) Then tips.dodaj(400, 450, 1, 1, 1)
			If KeyHit(KEY_Q) Then hud.dodajPunkty(1000)
			If KeyHit(KEY_H) Then heliManager.start()
			
			If KeyDown(KEY_UP) Then TAssistant.windaY:-1; Print "TAssistant.windaY = "+TAssistant.windaY
			If KeyDown(KEY_down) Then TAssistant.windaY:+1; Print "TAssistant.windaY = "+TAssistant.windaY
			If KeyDown(KEY_LEFT) Then TAssistant.windaX:-1; Print "TAssistant.windaX = "+TAssistant.windaX
			If KeyDown(KEY_RIGHT) Then TAssistant.windaX:+1; Print "TAssistant.windaX = "+TAssistant.windaX
			
			If KeyHit(KEY_1) Then dajAward.mainLoop( 2 )
			If KeyHit(KEY_2) Then dajAward.mainLoop( 5 )
			
		End If
		
		hud.rysujHelpTip()
		
		If fade Then
			SetAlpha fade
			SetBlend ALPHABLEND
			SetScale 1,1
			SetRotation 0
			SetColor 0,0,0
			DrawRect 0,0,800, 600
			
			SetColor 255, 255,255
			SetAlpha 1
		End If
		
		If mouse.rightPressed And (( Not TPowerUp.hotSpotPick) Or (Not TPowerUp.propagandaPick)) Then
			FlushMouse()
			mapPopUp.mainLoop( hud.txtRightClickTitle, hud.txtRightClick, 1 )
		End If
		mouse.updateAddOn()
		mouse.draw()

		Flip
		AspectCls()
	Forever
	
End Function


Function switchScreenCheck()

	If ((KeyDown(KEY_LALT) Or KeyDown(KEY_RALT)) And KeyDown(KEY_ENTER)) Or (KeyDown(91) And KeyHit(KEY_f)) Then 
		FlushKeys()
		full = Not full
		optionsScreen.openScreen()
		If full Then TButtonImage(optionsScreen.form.button("6")).text = "v"
		If Not full Then TButtonImage(optionsScreen.form.button("6")).text = ""
		If full Then TButtonImage(inGameOptions.form.button("6")).text = "v"
		If Not full Then TButtonImage(inGameOptions.form.button("6")).text = ""



	End If	
	
	
	If KeyDown(KEY_LALT) And KeyDown(KEY_F4) Then End
	If KeyHit(KEY_F4) Then FlushKeys()
	
End Function


Type TTxtFile
	
	Field txt:String[]
	
	Method lines()
		Return Len(txt)	
	End Method
End Type


Function loadTxtFile:TTxtFile(url:String)
	
	Local txtFile:TTxtFile = New TTxtFile
	Local txt:String = LoadText(url)
	Local lista:TList = CreateList()
	Local t:String = ""
	
	For Local i = 0 To txt.length-1
		If Chr(txt[i]) = "~n" Then
			lista.addlast(t)
			t = ""
		Else
			t:+Chr(txt[i])
		End If
	Next
	If t <> "" Then lista.addlast(t)
	
	Local tab:String[lista.count()]
	Local i = 0
	
	For Local tt:String = EachIn lista
		tab[i] = tt
		i:+1
	Next
	
	txtFile.txt = tab
	Return txtFile
	
End Function


Function readTxtData:String(txtFile:TTxtFile, n)
	
	If n = 0 Or n >Len(txtFile.txt) Then Return "(BEYOND TEXT ARRAY LENGTH!)"
	Return txtFile.txt[n-1]
	
End Function


Function focusCheck:Object(id,data:Object,context:Object )

	If AppTerminate() Then EndProgram()
	
		
	If AppSuspended() And (Not enteredLostFocus) Then lostFocus()
	
End Function

Global enteredLostFocus = False

Function lostFocus()
	
	enteredLostFocus = True
	Local txtF:TTxtFile = loadTxtFile( bdir + "data/texts.txt")
	Local txt:String = readTxtData( txtF, 622 )
	Local pm:TPixmap = GrabPixmap(0,0,800, 600)
'	If Not pm Then pm = CreatePixmap(800, 600, PF_RGBA8888); ClearPixels(pm, 0)
	Local im:TImage= LoadImage(pm)
	songManager.pauseChannels()
	
	globalSnd.pause()
	
	Repeat
		
		Cls()
		deltatime.update()
		delta = deltatime.currDelta()
		mouse.fetchState()	
		
		SetColor 255, 255, 255
		SetAlpha 1
		SetScale 1,1
		SetRotation 0
		SetBlend ALPHABLEND
		DrawImage im, 0, 0
		SetAlpha 0.5
		SetColor 0,0,0
		DrawRect 0,0,800, 600
		SetColor 255, 255, 255
		SetAlpha 1
		focusFont.DrawText( txt, 400, 290 )
		Flip()
		AspectCls()		

		If AppTerminate() Then EndProgram()
	
		If Not AppSuspended() Then 
			enteredLostFocus = False
			songManager.resumeChannels()
			globalSnd.resume()
			Return
		End If
	
	Forever
		
	
End Function



' -----------------------------------------------------------------------------
' SetIcon
' -----------------------------------------------------------------------------
Function SetIcon(iconname$, TheWindow%)	
	?Win32
	Local icon=ExtractIconA(TheWindow,iconname,0)
	Local WM_SETICON = $80
	Local ICON_SMALL = 0
	Local ICON_BIG = 1
	sendmessage(TheWindow, WM_SETICON, ICON_BIG, icon)
	?
End Function

'call it like this



' TODO:
' - aktywne znaki stopu do zarzadzania trasa
' - domki sluzace tylko do zwiekszania dlugosci trasy
' - akcja "insert" - plus dla on over na sciezce
' - context menu dla "insert" jezeli przez ulice przebiega wiecej niz jedna sciezka

' WE NEED:
' - zbuffer dla poprawnego rysowania obiektow, sciezek, tras, itp.
' - nowa mape swiata w celu ulatwienia wyszukiwania tras, obiektow, odcinkow
' - nowy sposob zarzadzania zadaniami oraz zapamietywanie ich kolejnosci
' - zapamietywanie tras w taki sposob, aby latwo im bylo zrobic mouse over
' - lista (klikalnych) znakow stop 




' TODO
' - przypisywanie pasazera do taxi
' - pomniejszanie przypisanych pasazerow, tak aby zajmowali mniej miejsca
' - rysowanie tla gry

' - add/swap context menu in route management - jezeli klikany budynek jest wsrod celow klientow, to add/swap, a jezeli nie, to swap

' - redesign drawing pipeline: implementacja z-buffera

' - BUG: zabieranie / wysadzanie pasazerow - Pizza House, Domek po prawej
' - BUG: brak akcji insert w route-management