##########################################################################
#	System.py 	Blender 2.66a
#
#	Created by Florian Voelker (iFlowProduction)
#	Games, Downloads and co. at http://iflowproduction.de
#
#	Released under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported (CC BY-NC-SA 3.0).
#	http://creativecommons.org/licenses/by-nc-sa/3.0/
#	
#	Feel free to change it for your own application(s), but leave this 
#	Header and inform others about the license.
#	If you use this code, please include this information header and don't change the license.
#
#	If you have any questions, please contact me.
#
#	Version 1.0
##########################################################################

from bge import logic
from bge import events

import sqlite3 as SQL
import sys
import GameLogic
import Rasterizer
import mathutils

import Cloth

# get the path to the blend directory
mainDir = GameLogic.expandPath("//")

#Activate/Deactivate the Debug and Error-visibility (1 = True/ 0 = False)
Debug = 0
Errors = 1

def onePositive(cont):
  for Keyboard in cont.sensors:
    if Keyboard.positive:
      return True
	
## Frees the Library-list
def FreeLibs():
	try:
		for lib in GameLogic.LibList():
			if GameLogic.LibFree(lib):
				if Debug:
					print('Libraries Free')
	except:
		if Errors:
			print('Cant free Libraries')
				
## Szenario laden	
def LoadReadSzenario(cont):
	obj = cont.owner
	
	#--------------------------------------------------------------------
	#Get the properties for Szenario-Selection
	SzenarioID = obj['SzenarioID']			#The current Szenario-ID
	
	#--------------------------------------------------------------------
	#Connect to the Database
	con = SQL.connect(mainDir + "Database\Szenarios.db")
	
	cur = con.cursor()
	#Load the Database-row with the choosen "Auto-ID"
	cur.execute("SELECT * FROM Szenarios WHERE SzenarioID=:Id", {"Id": SzenarioID})
	con.commit()

	data = cur.fetchone()

	#--------------------------------------------------------------------
	#Define and save the loaded Database-row-Data
	SzenarioName = data[1]
	File = data[2]
	
	#Close the Database-Connection
	if con:
		con.close()
	
	if Debug:
		print("")
		print(":---------Szenario_Start---------:")
		print(File + " Loaded")
	
	#send message after libload
	def finish_message():
		logic.sendMessage("Loadscreen.Off")
		
	#Load the Library
	try:
		logic.LibLoad(mainDir + "Szenarios/" + (File) + ('/') + (File) + ".blend", "Scene", load_actions=True, verbose=Debug, load_scripts=True)#.onFinish = finish_message
		
		#If LOD is available:
		try:
			if Debug:
				print("Debug-Point Line 92 'Mesh'")
			logic.LibLoad(mainDir + "Szenarios/" + (File) + ('/') + (File) + "_LOD_Lib.blend", "Mesh", load_actions=True, verbose=Debug, load_scripts=True)#.onFinish = finish_message
		except:
			if Errors:
				print("No LOD-Lib available!")
	except:
		if Errors:
			print("Error: " + File + " failed to Load!")
	
	finish_message()
	
	#print(logic.getCurrentScene().objects)
	
	if Debug:
		print(File)
		print("----------Szenario_End----------")
		print("")
		
## Actor laden	
def LoadReadActor(cont):
	scene = logic.getCurrentScene()
	objList = scene.objects
	obj = cont.owner
	
	#--------------------------------------------------------------------
	#Get the properties for Actor-Selection
	ActorID = obj['ActorID']			#The current Actor-ID
	
	if onePositive(cont):
		return
	
	#if "Vehicle" in obj:
	#	if obj["Active"] == False:
	#		return
	
	#--------------------------------------------------------------------
	#Connect to the Database
	con = SQL.connect(mainDir + "Database\Actor.db")
	
	cur = con.cursor()
	#Load the Database-row with the choosen "Actor-ID"
	cur.execute("SELECT * FROM Actor WHERE ActorID=:Id", {"Id": ActorID})
	con.commit()

	data = cur.fetchone()

	#--------------------------------------------------------------------
	#Define and save the loaded Database-row-Data
	ActorName = data[1]
	File = data[2]
	
	#Close the Database-Connection
	if con:
		con.close()
	
	if Debug:
		print("")
		print(":---------Actor_Start---------:")
		print(File + " Loaded")
		
	#Load the Library
	try:
		logic.LibLoad(mainDir + "Objects/Actor/" + ('/') + (File) + ".blend", "Scene", load_actions=True, verbose=Debug, load_scripts=True)
	except:
		if Errors:
			print("Error: " + File + " failed to Load!")
	
	if Debug:
		print(File)
		print("----------Actor_End----------")
		print("")
	
	
	# get actuator "Add" for adding an object
	spawn = cont.actuators["Add"]
		
	spawn.object = "Player"
	spawn.instantAddObject()
	
	logic.sendMessage("Ammo_Count.Update")
	logic.sendMessage("Actor.added")
	logic.sendMessage("Weapons.Reload")
	
	# activate Camera to Actor
	Active_Pos = objList["Active_Pos"]
	Active_Pos["Pos_Name"] = "Actor_Mesh"
	
	if "Vehicle" in obj:
		obj.state = 2
	try:
		Cloth.LibLoadClothes()
	except:
		if Debug:
			print("Clothes maybe already loaded")
			
	#Cloth.Load(cont)
	#Cloth.Replace()
	
## Activate the Cursor
def CursorOn():
	Rasterizer.showMouse(1)

## Deactivate the Cursor	
def CursorOff():
	Rasterizer.showMouse(0)

## Checks the Zoom - Propertie
def ZoomCheck(cont):
	scene = logic.getCurrentScene()
	obj = cont.owner
	Zoom = obj['Zoom']
	
	if Zoom <= 1:
		obj['Zoom'] = 1
	if Zoom >= 10:
		obj['Zoom'] = 10	
		scene.active_camera = "FPC-Actor"
	else:
		scene.active_camera = "Cam3rdPerson"
	
## Set the "MinimapCamPosition" to active object
def CamToActivePosition(cont):
	scene = logic.getCurrentScene()
	objList = scene.objects
	obj = cont.owner
	
	Pos_Name = obj['Pos_Name']
	
	if Pos_Name != "Actor_Mesh":
		return
	
	try:
		PosOBJ = objList[Pos_Name]
		obj.position = PosOBJ.position
	except:
		if Errors:
			print("Can't find position! CamToActivePosition")

def CalculateVector(E1, E2):
	Vector = E2 - E1
	
	#print (Vector)
	return Vector
			
def TrackToAimPos(cont):
	scene = logic.getCurrentScene()
	objList = scene.objects
	obj = cont.owner
	
	try:
		player = objList["Actor_Mesh"]
		hit = objList["bullethitpoint"]
		
		ori = CalculateVector(player.position, hit.position)

		vect = [ori[0],ori[1],0]
		player.alignAxisToVect(vect,0)
	except:
		if Debug:
			print("Cant track aim")
		
def end_Actor():
	scene = logic.getCurrentScene()
	objList = scene.objects
	
	try:
		player = objList["Actor_Mesh"]
		player.endObject()
	except:	
		if Debug:
			print("Cant end Actor")