local LogInfo = LogInfo or print
local LogDebug = LogDebug or print
local pairs, type, assert, error, tostring = pairs, type, assert, error, tostring
local require = require

module((...))

-- 
-- Connects to the database
-- @param datasource is an instance of LuaOrm.DBMS.DataSource
-- @param dataBase is a table with:
--    @field driver the SQL driver to use (i.e."{SQL Server}")
--    @field server the ip address of the database server (i.e. 192.168.20.20)
--    @field database the database to connect to (i.e. mmprodat)
--    @field uid the user id to login with
--    @field pwd the user password to login with
-- @param driver is the LuaSQL driver to use. By default is "inconcertPool" (which uses AdmConnections service) but it also can be "sqlite3"
function Connect(datasource, dataBase, driver)
	local driver = driver or "inconcertPool"
	local dbms
	if driver == "inconcertPool" then
		dbms = require "LuaOrm.DBMS.SqlServer"
	elseif driver == "sqlite3" then
		dbms = require "LuaOrm.DBMS.Sqlite3"
	elseif driver == "mysql" then
		dbms = require "LuaOrm.DBMS.MySql"
	else
		error("unknown driver specified: "..tostring(driver))
	end
	local conn_string = MakeConnectionString(dataBase)
	LogInfo("Connecting to: driver " .. driver .. ", connection string: " .. conn_string)
	return datasource:InitRdbmsLayer(driver, conn_string, dbms, dataBase)
end

--
-- Creates a "connection string" for connecting to a database
-- @param dataBase is a table containing the database info (see method Connect)
function MakeConnectionString(dataBase)
	if type(dataBase) == "string" then
		return dataBase
	end
	assert(type(dataBase) == "table", "'database' parameter must be a table or a string")
	local connectionString = ""
	
	for property, value in pairs(dataBase) do
		connectionString = connectionString .. property .. "=" .. value .. ";"
	end
	return connectionString
end

--
-- Validates an array of data sources.
-- @param dataSources is an array of instances of LuaOrm.DBMS.DataSource
function ValidateDataSources(dataSources)
	dataSources = dataSources or {}
	assert(type(dataSources) == "table", "'dataSources' parameter must be a table or nil")
	
	for k, dataSource in pairs(dataSources) do
		dataSource:Validate()
	end
end

--
-- Copies the key-values from one table to another.
-- @tablesOrigin is the source table
-- @tablesDestination is the destination table
function AddTables(origin, destination)
	assert(type(destination) == "table", "'tablesDestination' parameter must be a table")
	if type(origin) == "table" then
		for k, v in pairs(origin) do
			LogDebug("Adding table: " .. k)
			destination[k] = v
		end
	end
end
