
local oo = require "loop.base"

require "LuaOrm.Mapper"
require "LuaOrm.Date"
require "LuaOrm.DBMS.DataSource"

local m_connectionManager = require("LuaOrm.Connection")
local rpairs = require"LuaOrm.Associations.AssociationArray".Iterator
local m_dataSource = oo.new(LuaOrm.DBMS.DataSource) 

local m_dataBase = {
	driver = "mysql",
	server = "localhost",
	port = 3306,
	database = "MMProDat_dbo",
	uid = "SiteMonitor",
	pwd = "3com"
}
--local m_dataBase = "MMProDat_dbo"
local m_mapper = nil
local m_models = {}


local ok, err = m_connectionManager.Connect(m_dataSource, m_dataBase, "mysql")
if not ok then
	error("Failure connecting to database: "..err)
end

m_models.IndicatorAttribute = LuaOrm.Model {
	tableName = "IndicatorAttribute",
	dataSource = m_dataSource,
	Associations = {
		hasOne("DBAttribute", nil, true),
		--hasMany("GroupPermission", nil, true),
		--hasMany("GroupApplication", nil, true)
	},
	Attributes = {
		--ImageGroup = function(entity) 
			--return {name = 'NON_SYSTEM_GROUP', value = ''}
		--end
	}
}

m_models.DBAttribute = LuaOrm.Model {
	tableName = "DBAttribute",
	dataSource = m_dataSource,
	Associations = {
		belongsToOne("IndicatorAttribute", nil, true),
	},
	Attributes = {
		
	}
}

m_mapper = LuaOrm.Mapper.new()
m_connectionManager.ValidateDataSources({m_dataSource})

function test()
	
	local id = "b0db7232-875a-4bc8-924b-ade344362ffb"
	--os.execute("pause")
	local rows = m_models.IndicatorAttribute:FindAll("VCC = ? Order By Name Asc", { "system" })
	assert(type (rows) == "table", "result is not a table")
	print (json.encode(rows))
	--print(rows[1].TimeStamp)
	--print(os.date("!%Y-%m-%d %H:%M:%S", rows[1].TimeStamp:time()))
end


function testPagedRequests()
    local indicatorModel = m_models.IndicatorAttribute
    local pagedInteractionsByIndicator = indicatorModel:FindAllPaged("VCC = ? AND DBAttribute.Field = ?", {"System", "AbandonedPercent"}, 10)
    if (pagedInteractionsByIndicator) then
        local pagedRows = pagedInteractionsByIndicator:GetPage()
        while (pagedRows) do
            print("---------------------------------------------")
            print("=== Rows in this page:"..tostring(#pagedRows))
            local i = 0
            for k, v in ipairs(pagedRows) do
                print("Indicator :"..i)
                i = i + 1
                --print("        "..json.encode(v))
            end
            pagedRows = pagedInteractionsByIndicator:NextPage()
        end
    end
end

--test()
testPagedRequests()