#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#       untitled.py
#       
#       Copyright 2011 Johannes ter Haak <jojo@jojo3>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.
#       
#       


import sqlite3
import os.path
import os
import sys
import pygame
import time
import datetime
import argparse

path = os.path.dirname(__file__)
if path != "":
	os.chdir(path)

from monde import * 
from menu import * 
from player import * 

pygame.font.init()
#pygame.init()

parser = argparse.ArgumentParser(description='JojoSettlers')
parser.add_argument("-f","--file","-file", dest='file',default="map.sqlite" , action='store' , help='Map file, die geladen weden soll')
args = parser.parse_args()
map_file = args.file

def main(map_file):
	font = pygame.font.Font("FreeMono.ttf",12)
	size = width, height = 1024, 768  	
	#size = width, height = 1440, 900  	
	black = 0, 0, 0	
	screen = pygame.display.set_mode(size) 	# ,pygame.FULLSCREEN
	pygame.display.set_caption("JojoSettlers")
	# monde, menu und player
	monde = Monde(map_file)
	s=2
	for r in monde.monde:
		for o in r:
			if o.islink() == False:
				s = o.zoom
				break
	monde.Spielbrett(s)
	
	menu = Menu()
	players = Players(monde.wege,map_file)
	monde.players = players
	clock = pygame.time.Clock()
	monde.zoom = s
	monde.do_zoom(menu.player,(width,height))
	
	# set events 
	pygame.time.set_timer(pygame.USEREVENT+1, 1000)		# update player event
	pygame.time.set_timer(pygame.USEREVENT+2, 2000)		# update monde event
	pygame.time.set_timer(pygame.USEREVENT+3, 200)		# next multiframe player event
	pygame.time.set_timer(pygame.USEREVENT+4, 500)		# netx multiframe monde event
	# sonstige vars
	ex = False
	debug_tab = False
	fullscreen = False
	
	
	## MAIN LOOP
	#========================
	while 1:
		clock.tick(60)
		
		##	Vars 
		multiframe_player_next = False
		multiframe_monde_next = False
		mouse =	pygame.mouse.get_pos()
		r=0
		if monde.zoom == 0:
			r = 10
		elif monde.zoom == 1:
			r = 20
		elif monde.zoom == 2:
			r = 40 	

		###		EVENTS
		for event in pygame.event.get():	
			if event.type == pygame.QUIT: sys.exit() 
			
			## keyboard
			elif event.type == pygame.KEYDOWN:
				# exit
				if event.key == pygame.K_ESCAPE: ex = True#sys.exit()
				# save
				if event.key == 115 : 
					monde.save(map_file,players.players) 
				# - -> zoom -
				elif event.key == 269:						
					if 0< monde.zoom <=2:
						monde.zoom = monde.zoom-1
						print "zoom - , f=" + str(monde.zoom)
						monde.do_zoom(menu.player,(width,height))
				# + -> zoom +	
				elif event.key == 270:							 
					if 0<= monde.zoom <2:
						monde.zoom = monde.zoom+1
						print "zoom + , f=" + str(monde.zoom)
						monde.do_zoom(menu.player,(width,height))
				# debug info auf tabdruck
				elif event.key == 9:								 
					debug_tab = True
				# Fullscreen
				elif event.key == 102:
					if fullscreen == False:
						pygame.display.set_mode((1024,768), pygame.FULLSCREEN|pygame.DOUBLEBUF|pygame.HWSURFACE)
						fullscreen = True
					else:
						pygame.display.set_mode((1024,768))
						fullscreen = False
				# debug 2
				elif event.key == 103:
					for p in players.players:
						for t in p.geb:
							for g in t:
								print t
			# debug					
			elif event.type == pygame.KEYUP:
				if event.key == 9:						# debug info auf tabdruck		 
					debug_tab = False
			

			## Mouse
			elif event.type == pygame.MOUSEBUTTONDOWN:
				# zoom out
				if event.button == 5 and (0< monde.zoom <=2):
					monde.zoom = monde.zoom-1
					print "zoom - , f=" + str(monde.zoom)
					monde.do_zoom(menu.player,(width,height))
				# zoom in
				elif event.button == 4 and (0<= monde.zoom <2):
					monde.zoom = monde.zoom+1
					print "zoom + , f=" + str(monde.zoom)
					monde.do_zoom(menu.player,(width,height))
			# update player
			elif event.type == pygame.USEREVENT+1:
				print "##updatde player"
				players.update(monde)
				print ""				
			# update monde
			elif event.type == pygame.USEREVENT+2:
				print "##update monde"
				monde.update(players.players)
				print ""
			# next frame in player multiframe
			elif event.type == pygame.USEREVENT+3:
				multiframe_player_next = True
			# next frame in monde multiframe
			elif event.type == pygame.USEREVENT+4:
				multiframe_monde_next = True
								
		# EXIT
		if ex == True:
			break

		# SCROLLEN
		monde.scroll(menu.player,(1024,768),15)
		
		# menu update & wird der Infomodus verlassen: beleuchtung normal
		menu_mode_before = menu.mode[:]
		menu.update()
		if ((menu_mode_before[0] != menu.mode[0]) and (menu_mode_before[0] == "info")):
			for t in monde.draw:
				if t.islink() == False:
					t.unhighlight()
		# leeren von monde.bauen			
		if (menu_mode_before != menu.mode):
			monde.bauen = []
		
		# FILL BLACK		
		screen.fill(black)
		
		# Monde zeichnen
		for o in monde.draw:
			if o.islink() == False:
				if monde.neu[o.typ].get("multifr") == 1:
					screen.blit(o.img[0],o.rect)	
					if  multiframe_monde_next == True: 
						o.img.append(o.img[0])
						del o.img[0]
				else:
					screen.blit(o.img,o.rect)

			# zeichne die "Reparaturen" an den Häusern 
			for rep in monde.draw_repair:
				if o.pos == rep[2]:
					screen.blit(rep[0],rep[1])	
				

		# Leute zeichnen (Reparatur integriert)
		for l in players.players[menu.player].leute.leute:
			if monde.neu[l.typ].get("multifr") != None:
				screen.blit(l.dimg,l.rect)
				if  multiframe_player_next ==True: 
					if len(l.img) != 1:
						del l.img[0]
			else:
				screen.blit(l.img,l.rect)
		
		###		MENU
		#==========================================00
		screen.blit(menu.background["img"],menu.background["rect"])
		
		for tab in menu.tablist:
			screen.blit(tab.img,tab.rect)
		
		for e in menu.infopannel[menu.mode[0]]:
			screen.blit(e.img,e.rect)
			
		menu.freearea["gold"].imprimer( "Gold: " + str(players.players[menu.player].cash))
		screen.blit( menu.freearea["gold"].img , menu.freearea["gold"].rect )
			
		if (menu.mode[1] != -1) and (menu.mode[0]=="b"):
			mangelware = players.players[menu.player].test_speicher( monde.neu[menu.mode[1]] )
		else:
			mangelware = []
		## Kosten anzeige beim Bauen
		if (menu.mode[0] == "bauen"):	
			menu.freearea["content"] = []
			if menu.mode[1] not in [0,-1]:
				head= {"img":menu.font.render(menu.names[menu.mode[1]],1,(0,0,0))}
				head["rect"]=head["img"].get_rect().move( menu.pos[0]+10 , menu.pos[1]+10 )	
				temp = Label(pos=(menu.pos[0]+20,menu.pos[1]+40),text="")
				temp.font_resize(20)
				temp.set_mode("colored")
				text = "Kosten:"
				for k in monde.neu[ menu.mode[1] ]:
					if k[:4] == "cost":
						if k[-3:].isdigit():
							if not (int(k[-3:]) in mangelware):
								text = text + "\n" + str(monde.neu[ menu.mode[1] ][k]) + " " + menu.waren[ int(k[-3:]) ]["name"]
							else:
								text = text + "\n<span style='color:#980100'>" + str(monde.neu[ menu.mode[1] ][k]) + "</span> " + menu.waren[ int(k[-3:]) ]["name"] + " ("+str( players.players[menu.player].spe.get( int(k[-3:]) ) )+")"
						else:
							text = text + "\n" + str(monde.neu[ menu.mode[1] ][k]) + " Gold"
				temp.imprimer(text)
				menu.freearea["content"].append(temp)
				screen.blit(head["img"],head["rect"])
				for con in menu.freearea["content"]:
					screen.blit(con.img,con.rect)
		
		## menu Bauen	
		if (menu.mode[0] == "bauen") and (mouse[1] < menu.pos[1]):
			if mangelware == []:
				monde.Bauen(menu.mode[1])
	
	
				for b in monde.bauen:
					if b.multiframe[0] == 0:
						screen.blit(b.img,b.rect)
					else:
						screen.blit(b.img[0],b.rect)
				
				for obj in monde.gebaut:
					if obj.islink() == False:
						if menu.mode[1] in [10]:	#Haus level 1
							players.players[menu.player].geb[menu.mode[1]][str(obj.pos)] = Haus(neu=monde.neu[menu.mode[1]], pos=obj.pos)						
				
						if menu.mode[1] in [15]:	# Markthaus
							players.players[menu.player].geb[menu.mode[1]][str(obj.pos)] = Markthaus(neu=monde.neu[menu.mode[1]], pos=obj.pos)
									
						if menu.mode[1] in [20]:	# Getreidefarm
							players.players[menu.player].geb[menu.mode[1]][str(obj.pos)] = Farm(neu=monde.neu[menu.mode[1]], pos=obj.pos)
	
						if menu.mode[1] in [21]:	# Mühle
							players.players[menu.player].geb[menu.mode[1]][str(obj.pos)] = Muehle(neu=monde.neu[menu.mode[1]], pos=obj.pos)		
	
						if menu.mode[1] in [22]:	# Bäcker
							players.players[menu.player].geb[menu.mode[1]][str(obj.pos)] = Baecker(neu=monde.neu[menu.mode[1]], pos=obj.pos)		
	
						if menu.mode[1] in [23]:	# Forsthaus
							players.players[menu.player].geb[menu.mode[1]][str(obj.pos)] = Forsthaus(neu=monde.neu[menu.mode[1]], pos=obj.pos)
							
						if menu.mode[1] in [-1]:	# Löschen
							geb = players.players[menu.player].get_geb(obj.pos)
							if geb != None:
								del players.players[menu.player].geb[ geb.typ ][str(obj.pos)]	
	
						if (menu.mode[1] != -1):	
							# aura
							if (monde.neu[ menu.mode[1] ].get("aura") != None):		# aura
								players.players[menu.player].geb[menu.mode[1]][str(obj.pos)].aura = kreis( monde.monde , [ obj.pos[0] + monde.neu[ menu.mode[1] ]["aura"][0]  ,  obj.pos[1] + monde.neu[ menu.mode[1]]["aura"][1] ], monde.neu[ menu.mode[1]]["aura"][2])
							# Kosten abrechnen
							for key in monde.neu[menu.mode[1]]:
								if key[:5] == "cost_":
									players.players[menu.player].speicherIO(int(key[-3:]),monde.neu[menu.mode[1]][key])
								elif key == "cost":
									players.players[menu.player].cash = players.players[menu.player].cash - monde.neu[menu.mode[1]][key]
															
				monde.gebaut = []
	
		
		elif menu.mode[0] == "info":
			if (pygame.mouse.get_pressed()[0] == True) and not (monde.get(menu.info_selected).rect.contains(pygame.Rect((mouse[0]-(r/2),mouse[1]-(r/2),r,r)))):  
				# ist sel gleich passiert nichts (dopplung vermeiden)		

				# AUSWAHL
				for o in monde.draw:	
					if o.islink() == False:
						if (o.rect.contains(pygame.Rect((mouse[0]-(r/2),mouse[1]-(r/2),r,r)))):
							if (o.size !=[1,1]) :
								## alles verdunkeln
								for o2 in monde.draw:
									if o2.islink() == False:
										o2.darken()
										
								# aus draw passende Koordinaten suchen 
								# gehe links nach
								if o.islink() == True:
									p = o.link
								else:
									p = o.pos
								#selection
								sel = monde.monde[ menu.info_selected[0] ][ menu.info_selected[1] ]
								#sel.unhighlight()		## Auswahl nicht mehr verdunkeln
								monde.monde[p[0]][p[1]].highlight()
								# die Aura des Gebäudes wird heller gezeichnet
								if players.players[menu.player].geb[ monde.monde[p[0]][p[1]].typ ].get( str(monde.monde[p[0]][p[1]].pos) ) != None:
									for a in players.players[menu.player].geb[ monde.monde[p[0]][p[1]].typ ][str(monde.monde[p[0]][p[1]].pos)].aura:
										if monde.monde[a[0]][a[1]].islink() == False:
											monde.monde[a[0]][a[1]].unhighlight()
									
								menu.info_selected = p
							else:
								# wird ein einser Feld oder gar nichts angewählt, so wird alles hell
								menu.info_selected = [0,0]
								for obj in monde.draw:
									if not obj.islink():
										obj.unhighlight()

							
							
			
			obj = monde.monde[ menu.info_selected[0] ][ menu.info_selected[1] ] 
			speicherlist = []
			geb = players.players[menu.player].geb[monde.monde[ menu.info_selected[0] ][ menu.info_selected[1] ].typ].get(str(menu.info_selected))
			if geb != None:
		
				head= [menu.font.render(menu.names[geb.typ],1,(0,0,0))]
				head.append(head[0].get_rect().move( (menu.pos[0]+menu.infopannel["pos"][0]+25+10) , menu.pos[1]+menu.infopannel["pos"][1]+10 ))
				x = menu.pos[0]+menu.infopannel["pos"][0]+25+10+20 ; y=menu.pos[1]+menu.infopannel["pos"][1]+head[1].height+20
				
				if geb.typ != 15:
					for s in geb.speicher:
						if geb.typ not in [10,11,15]:
							speicherlist.append(Speicherstand(icon=menu.waren[s]["img"] , quant=geb.speicher[s] , pos=(x,y) ))
						elif geb.typ in [10,11]:
							speicherlist.append(Speicherstand(icon=menu.waren[s]["img"] , quant=str(geb.zufrieden[s])+"%" , pos=(x,y) ))
						y = y + 50 + 10 
						if y > (menu.pos[1]+menu.infopannel["pos"][1]+200-50):
							y = menu.pos[1]+menu.infopannel["pos"][1]+head[1].height+20
							x = x + 150
				else:
					for s in players.players[menu.player].spe:	
						speicherlist.append(Speicherstand(icon=menu.waren[s]["img"] , quant=players.players[menu.player].spe[s] , pos=(x,y) ))
						y = y + 50 + 10 
						if y > (menu.pos[1]+menu.infopannel["pos"][1]+200-50):
							y = menu.pos[1]+menu.infopannel["pos"][1]+head[1].height+20
							x = x + 150		
								
				screen.blit(head[0], head[1])
				for s2 in speicherlist:
					screen.blit(s2.img,s2.rect)		
			
			
							
			if debug_tab == True:
				menu.infopannel["info"][0].set_mode("colored")
				menu.infopannel["info"][1].set_mode("colored")				
				obj = monde.monde[ menu.info_selected[0] ][ menu.info_selected[1] ] 
				menutext = "<span style='color:#FF0000'>pos : " + str(obj.pos) + "</span>\ntyp: " + str(obj.typ) + "\ndatei: " + str(obj.datei) + "\nbauen: " + str(obj.bauen) + "\nkorr: " + str(obj.korr) + "\nlink: " + str(obj.islink())
				menu.infopannel["info"][0].imprimer(menutext)
				geb = players.players[menu.player].geb[monde.monde[ menu.info_selected[0] ][ menu.info_selected[1] ].typ].get(str(menu.info_selected))
				if geb != None:
					if isinstance(geb,Farm) or isinstance(geb,Muehle):
						menutxt2 = "produktion: " + str(geb.prod) +"\nvitesse: " + str(geb.prodv) + "\naura: " + str(geb.aura) +"\nspeicher: " + str(geb.speicher) 
						menu.infopannel["info"][1].imprimer(menutxt2)
					elif isinstance(geb,Markthaus):
						menutxt2 = "speicher: " + str(geb.speicher) 
						menu.infopannel["info"][1].imprimer(menutxt2)
					elif isinstance(geb,Haus):
						menutxt2 = "speicher: " + str(geb.speicher) + "\nverbrauch: " + str(geb.verbrauch) + "\nzufrieden: " + str(geb.zufrieden) + "\nstimmung: " + str(geb.stimmung) + "\nmax_einwohner: " + str(geb.max_einwohner) + "\neinwohner: "  + str(geb.einwohner)
						menu.infopannel["info"][1].imprimer(menutxt2)
				else:
					menu.infopannel["info"][1].clear()
			else:
				menu.infopannel["info"][0].clear()
				menu.infopannel["info"][1].clear()
				
		elif menu.mode[0] == "conf":
			if menu.mode[1] == "save":
				monde.save(map_file,players.players) 
				menu.mode[1] = None
				
				
		

		pygame.display.flip()

	return 0



if __name__ == '__main__':
	main(map_file)
"""
import cProfile
cProfile.runctx('main(map_file)',globals(),locals())
# cProfile.runctx('Traeger(monde , start=anschluss_markt, stop=anschluss_haus , geb=[markthaus[0] , self]) ',globals(),locals())
"""
