#!/usr/bin/env python
# -*- coding: utf-8 -*-
#


import sqlite3
import os.path
import os
import random
import argparse

def create(maxx,maxy):
	
	baume = []
	for r in range(0,(maxx*maxy-200)):
		baume.append([random.randint(0,maxx),random.randint(0,maxy)])
	
	world=[]
	for x  in range(0,maxx):
		world.append([])
		for y in range(0,maxy):
			world[-1].append({"pos":[x,y],"datei":"bild/wiese-z2-n.png","size":[1,1],"type":1,"bauen":1,"prop": {}})
			
			if [x,y] in baume:
				s = random.randint(1,2)
				world[-1][-1]["datei"] = "bild/baum"+str(s)+"-z2-n.png"
				world[-1][-1]["type"] = 3+s # 4 oder 5
			
			"""
			if (1 < x < 5) and (1 < y < 5):
				world[-1][-1]["link"] = [2,2]
			if (x == 2) and (y == 2):
				world[-1][-1]["link"] = None
				world[-1][-1]["datei"] = "bild/haus-lvl0-z2-n.png"
				world[-1][-1]["size"] = [3,3]
				world[-1][-1]["type"] = 10
				world[-1][-1]["bauen"] = 0	
			if (7 <= x <= 8) and (2 <= y <= 3):
				world[-1][-1]["link"] = [7,2]	 
			if (x == 7) and (y == 2):
				world[-1][-1]["link"] = None
				world[-1][-1]["datei"] = "bild/muele-z2-n.png"
				world[-1][-1]["size"] = [2,2]
				world[-1][-1]["type"] = 21
				world[-1][-1]["bauen"] = 0		 
			"""
	del x,y	
	players={0:{"name":"jojo","cash":100000,"pop":0,"ausg":0,"eing":0,"spe":{115:15}}}
	return {"monde":world,"players":players}

def create_file(filename):
	con = sqlite3.connect(filename)
	con.row_factory = sqlite3.Row

	c= con.cursor()
	c.execute('''create table monde(pos text, datei text, type text , bauen texte , size text,link text)''')
	c.execute('''create table players(num integer, name text,cash integer, pop integer , ausg integer , eing integer, spe text)''')
	# Gebäude: [10,11,15,20,21,23]:
	c.execute('''create table farmen(player integer, typ integer, pos text , prod integer , prodv integer, spe text, reqfeld integer, aura text)''')
	c.execute('''create table forsthauser(player integer, typ integer, pos text , prod integer , prodv integer, spe text, reqfeld integer, aura text)''')
	c.execute('''create table muehlen(player integer, typ integer, pos text , prod integer , prodv integer, spe text, reqgut integer, aura text)''')
	c.execute('''create table baecker(player integer, typ integer, pos text , prod integer , prodv integer, spe text, reqgut integer, aura text)''')
	c.execute('''create table markthauser(player integer, typ integer, pos text , spe text, aura text)''')
	c.execute('''create table hauser(player integer, typ integer, pos text , spe text, aura text , verbrauch text , zufrieden text, stimmung integer , max_einwohner integer , einwohner integer)''')
	con.commit()
	c.close()

def write_monde(filen,monde,players):
	if os.path.exists(filen) == False:
		print "creating file"
		create_file(filen)
	else:
		os.rename(filen,filen+".old")
		create_file(filen)
	con = sqlite3.connect(filen)
	con.row_factory = sqlite3.Row
	c= con.cursor()
	c.execute('''delete from monde''')
	con.commit()
	for r in monde:
		for e in r:
			if e.get("link") == None:
				c.execute('''insert into monde values(?,?,?,?,?,?)''',[str(e["pos"]),str(e["datei"]),str(e["type"]),str(e["bauen"]),str(e["size"]),None])
			elif e.get("link") != None:
				c.execute('''insert into monde values(?,?,?,?,?,?)''',[str(e["pos"]),None,None,None,None,str(e["link"])])
	con.commit()
	c.execute('''delete from players''')
	con.commit()
	for p in players:
		c.execute('''insert into players values(?,?,?,?,?,?,?)''',[p,str(players[p]["name"]),players[p]["cash"],players[p]["pop"],players[p]["ausg"],players[p]["eing"],str(players[p]["spe"])])
	con.commit()
	c.close()


def load_monde(filen):
	if os.path.exists(filen) == False:
		print "file specified does not exist"
		return False
	else:
		con = sqlite3.connect(filen)
		con.row_factory = sqlite3.Row
		c= con.cursor()
		c.execute('''select * from monde''')
		
		ok = True
		monde = []
		while ok == True:
			r = c.fetchone()
			
			if r != None:
				keys= r.keys()
				t={}
				for k in keys:
					t[k]=str(r[k])
					# stings bleiben strings
					if t[k][0] == "[" and t[k][-1] == "]":		# arrays
						t[k] = t[k].strip("[]").split(",")
						t[k][0] = int(t[k][0])
						t[k][1] = int(t[k][1])
					elif t[k].isdigit() or (t[k][0] == "-" and t[k][1:].isdigit()):			# ints
						t[k] = int(t[k])
				monde.append(t)
			else:
				ok = False 
		
		#print monde
		
		## neues array initialisieren
		#--------------------
		monde2=[]
		k=0
		for j in monde:
			if j != {}:
				if j["pos"][0] > k:
					k =  j["pos"][0]
		
		n=0
		for m in monde:
			if m != {}:
				if m["pos"][1] > n:
					n = m["pos"][1]
		
		
		for each in range (0,k+1):
			monde2.append([])
			for each in range(0,n+1):
				monde2[-1].append([])
				
		## neues array füllen
		#--------------------
		
		for l in monde:
			if l != {}:
				monde2[ l["pos"][0] ][ l["pos"][1] ] = l

		con.commit()
		c.close()
		return monde2
	

parser = argparse.ArgumentParser(description='JojoSettlers - map tool')
parser.add_argument("-f","--file","-file", dest='file',default="map.sqlite" , action='store' , help='Map file, die geladen weden soll')
parser.add_argument("-s","--size","-size", dest='size',default="20x20" , action='store' , help='Grösse der Karte (standart 20x20)')
args = parser.parse_args()
map_file = args.file

map_size = args.size.split("x")
map_size[0] = int(map_size[0])
map_size[1] = int(map_size[1])

temp = create(map_size[0],map_size[1])
monde = temp["monde"]
players = temp["players"]
write_monde(map_file,monde,players)
#print load_monde("test2.sql")
