##########################################################################
#	Weapon.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 Settings
import System

# 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

#Connects the "BulletHole" to its hitObject
def ConnectToCollision(cont):
	obj = cont.owner
	
	sen = cont.sensors["Collision"]
	parent = sen.hitObject
	
	obj.setParent(parent, False, False)

#Loads the Weapons from file	
def LibLoadWeapons():

	File = "Waffen"
	
	try:
		logic.LibLoad(mainDir + "Objects/Waffen/" + ('/') + (File) + ".blend", "Mesh", load_actions=True, verbose=Debug, load_scripts=True)
	except:
		if Errors:
			print("Error: " + File + " failed to Load! Maybe loaded twice.")
	print("LibLoaded")
	
def LibLoadWeaponsHUD():

	File = "Waffen_HUD"
	
	try:
		logic.LibLoad(mainDir + "Objects/Waffen/" + ('/') + (File) + ".blend", "Mesh", load_actions=True, verbose=Debug, load_scripts=True)
	except:
		if Errors:
			print("Error: " + File + " failed to Load! Maybe loaded twice.")
	print("LibLoaded")

def LoadMaxWeaponCount():
	#--------------------------------------------------------------------
	#Connect to the Database User/Actor_Design
	con = SQL.connect(mainDir + "Database/Weapon.db")
	
	cur = con.cursor()
	#Load the Database-row with the choosen "User-ID"
	cur.execute("SELECT COUNT(*) FROM Weapon")
	con.commit()
	
	data = cur.fetchone()
	max = data[0]
	
	#Close the Database-Connection
	if con:
		con.close()
	
	return max	
	
#specs: 0 = Object, 1 = Object_X, 2 = Ammo_Orig, 3 = Ammo_Limit, 4 = Shootable
#default details	
def LoadWeaponSpecsDB(WeaponID):
	
	#--------------------------------------------------------------------
	#Connect to the Database User/Actor_Design
	con = SQL.connect(mainDir + "Database/Weapon.db")
	
	cur = con.cursor()
	#Load the Database-row with the choosen "User-ID"
	cur.execute("SELECT * FROM Weapon WHERE ID=:id", {"id":WeaponID})
	con.commit()
	
	data = cur.fetchone()
	
	Object = data[1]
	Object_X = data[2]
	Ammo_Orig = data[3] 
	Ammo_Limit = data[4]
	Shootable = data[5]
	
	#Close the Database-Connection
	if con:
		con.close()
	
	specs = ([Object, Object_X, Ammo_Orig, Ammo_Limit, Shootable])
	
	return specs

#stat: 0 = Available, 1 = Ammo
#User saved weapon-details
def LoadWeaponStatDB(WeaponID):
	cont = logic.getCurrentController()
	obj = cont.owner
	
	#--------------------------------------------------------------------
	Settings.ReadLastUserFile(cont)
	UserID = obj['UserID']
	#--------------------------------------------------------------------
	try:
		#Connect to the Database User/Weapons
		con = SQL.connect(mainDir + "Database/User.db")
		
		cur = con.cursor()
		#Load the Database-row with the choosen "User-ID"
		cur.execute("SELECT * FROM Weapons WHERE UserID=:Uid AND WeaponID=:Wid", {"Uid":UserID, "Wid":WeaponID})
		con.commit()

		data = cur.fetchone()
		
		Available = data[2]
		Ammo = data[3]
		
		#Close the Database-Connection
		if con:
			con.close()
			
		stat = ([Available, Ammo])
	
	except:
		
		stat = ([0, 0])
		
	return stat

def updateWeaponStatDB():
	cont = logic.getCurrentController()
	obj = cont.owner
	#--------------------------------------------------------------------
	Settings.ReadLastUserFile(cont)
	UserID = obj['UserID']
	Ammo = obj['Ammo']
	WeaponID = obj['WeaponID']
	#--------------------------------------------------------------------
	#Connect to the Database User/Weapons
	con = SQL.connect(mainDir + "Database/User.db")
	
	cur = con.cursor()
	#Load the Database-row with the choosen "User-ID"
	cur.execute("UPDATE Weapons SET Ammo =:Ammo WHERE UserID =:ID and WeaponID=:Wid", {"Ammo":Ammo, "ID":UserID, "Wid":WeaponID})
	con.commit()
	logic.sendMessage("Ammo_Count.Updated")

def changeWeaponID():
	cont = logic.getCurrentController()
	obj = cont.owner
	#--------------------------------------------------------------------
	if onePositive(cont):
		return
	#--------------------------------------------------------------------
	WeaponID = obj['WeaponID']
	Change = obj['Change']
	Ammo = obj['Ammo']
	#--------------------------------------------------------------------
	updateWeaponStatDB()
	#--------------------------------------------------------------------
	if Change:
		obj['WeaponID'] = WeaponID + 1
	elif Change == False:
		obj['WeaponID'] = WeaponID - 1
	
#returns array of available weapons
def AvailableWeapons():
	cont = logic.getCurrentController()
	obj = cont.owner	
	#--------------------------------------------------------------------
	Settings.ReadLastUserFile(cont)
	UserID = obj['UserID']
	WeaponID = []
	#--------------------------------------------------------------------
	#Connect to the Database User/Actor_Design
	con = SQL.connect(mainDir + "Database/User.db")
	
	con.row_factory = SQL.Row
	
	cur = con.cursor()
	#Load the Database-row with the choosen "User-ID"
	cur.execute("SELECT * FROM Weapons WHERE UserID=:Uid AND Available=1", {"Uid":UserID})
	con.commit()

	rows = cur.fetchall()
	
	#Close the Database-Connection
	if con:
		con.close()
	
	for row in rows:
		WeaponID.append(row["WeaponID"])
	
	return WeaponID

def transferWeaponIDtoHUD(WeaponID):
	scenelist = GameLogic.getSceneList()
	
	# get current scene
	scenelist = GameLogic.getSceneList()
	
	for s in scenelist:      
		if s.name == 'HUD':
			scene = s
	
	objList = scene.objects
	
	dummy = objList["HUD_WeaponDummy"]
	dummy['WeaponID'] = WeaponID

def transferAmmoCounttoHUD():
	cont = logic.getCurrentController()
	obj = cont.owner	
	#--------------------------------------------------------------------
	Ammo = obj['Ammo']
	#--------------------------------------------------------------------
	scenelist = GameLogic.getSceneList()
	# get current scene
	scenelist = GameLogic.getSceneList()
	
	for s in scenelist:      
		if s.name == 'HUD':
			scene = s
	
	objList = scene.objects
	#--------------------------------------------------------------------
	if Ammo < 0:
		Ammo = 0
	#--------------------------------------------------------------------
	dummy = objList["Text_Ammo"]
	obj['Ammo'] = Ammo
	dummy['Text'] = Ammo
	
def weapon_name(WeaponID):
	cont = logic.getCurrentController()
	scene = logic.getCurrentScene()
	obj = cont.owner
	objList = scene.objects
	
	#--------------------------------------------------------------------
	WSpecs = LoadWeaponSpecsDB(WeaponID)
	
	Object = WSpecs[0]
	Object_X = WSpecs[1]
	#Ammo_Orig = WSpecs[2]
	#Ammo_Limit = WSpecs[3]
	#--------------------------------------------------------------------
	WStats = LoadWeaponStatDB(WeaponID)
	
	Available = WStats[0]
	#Ammo = WStats[1]
	#--------------------------------------------------------------------
	if Available:
		name = Object
		obj['Shoot'] = WSpecs[4]
	else:
		name = Object_X
		obj['Shoot'] = False
		
	return name
		
def correct_WeaponID(cont, WeaponID):
	obj = cont.owner
	maxW = LoadMaxWeaponCount()
	
	if WeaponID < 1:
		obj['WeaponID'] = maxW
		
	if WeaponID > maxW:
		obj['WeaponID'] = 1
	
	WeaponID = obj['WeaponID']
	return WeaponID
	
def replaceWeaponDummy():
	cont = logic.getCurrentController()
	scene = logic.getCurrentScene()
	obj = cont.owner
	objList = scene.objects
	#--------------------------------------------------------------------
	WeaponID = obj['WeaponID']
	Ammo = obj['Ammo']
	WStats = LoadWeaponStatDB(WeaponID)
	#--------------------------------------------------------------------
	try:
		try:
			WeaponID = correct_WeaponID(cont, WeaponID)
			#--------------------------------------------------------------------
			dummy = objList["WaffenDummy"]
			#--------------------------------------------------------------------
			name = weapon_name(WeaponID)
			dummy.replaceMesh(name,True,False)
			#--------------------------------------------------------------------
		except:
			if Errors:
				print("Can't replace Weapons. Maybe Actor not loaded?")
			
		transferWeaponIDtoHUD(WeaponID)
		obj['Ammo'] = WStats[1]
		logic.sendMessage("Weapon_Changed")
	except:
		if Errors:
			print("Can't replace Weapons. Maybe Actor not loaded and everything wrong?")
			
def replaceWeaponDummyHUD():
	cont = logic.getCurrentController()
	obj = cont.owner
	#--------------------------------------------------------------------
	WeaponID = obj['WeaponID']
	name = weapon_name(WeaponID)
	obj.replaceMesh(name,True,False)	

def replaceGetWeaponsObject(cont):
	obj = cont.owner	
	#--------------------------------------------------------------------
	WeaponID = obj['WeaponID']
	WSpecs = LoadWeaponSpecsDB(WeaponID)
	#--------------------------------------------------------------------
	object = WSpecs[0]
	obj.replaceMesh(object)
	
## Take a weapon
def GetWeapons(cont):
	obj = cont.owner
	#--------------------------------------------------------------------
	Settings.ReadLastUserFile(cont)
	UserID = obj['UserID']
	LoadToMax = obj['LoadToMax']
	LoadToDefault = obj['LoadToDefault']
	#--------------------------------------------------------------------
	WeaponID = obj['WeaponID']
	Ammo_Count = obj['Ammo_Count']
	WSpecs = LoadWeaponSpecsDB(WeaponID)
	WStats = LoadWeaponStatDB(WeaponID)
	#--------------------------------------------------------------------
	Ammo_Orig = WSpecs[2]
	Ammo_Limit = WSpecs[3]
	#--------------------------------------------------------------------
	Available = WStats[0]
	Ammo = WStats[1]
	#--------------------------------------------------------------------
	#Connect to the Database User/Weapons
	con = SQL.connect(mainDir + "Database/User.db")
	cur = con.cursor()
	
	#Sets the ammount of reloaded ammo
	#--------------------------------------------------------------------
	if LoadToDefault:
		Ammo_Count = Ammo_Orig
		Ammo = Ammo_Orig
	elif LoadToMax:
		Ammo_Count = Ammo_Limit
		Ammo = Ammo_Limit
	else:
		Ammo = Ammo + int(Ammo_Count)
		if Ammo > int(Ammo_Limit):
			Ammo = Ammo_Limit
	#--------------------------------------------------------------------
	
	if Available:
		cur.execute("UPDATE Weapons SET Ammo =:Ammo WHERE UserID =:ID and WeaponID=:Wid", {"Ammo":Ammo, "ID":UserID, "Wid":WeaponID})
	else:
		cur.execute("INSERT INTO Weapons (UserID, WeaponID, Available, Ammo) VALUES (?,?,1,?)", (UserID, WeaponID, Ammo_Count))
	
	con.commit()
	
	obj.endObject()
	logic.sendMessage("Weapons.Reload")