require "LuaOrm.Date"
module(..., package.seeall)
local m_table = require "helpers.table"

--=============================================================================
--[[
	Esta funcion valida si la fecha recibida por parámetro, se encuentra dentro de horario de verano,
	en el timezone recibido por parámetro.
	Busca dentro de la tabla historica "HistoricalDaylight".
--]]
function IsEnabledDateBetweenDaylightSavingTime (dateValue, timezone)
	assert(dateValue)
	if type(timezone) ~= "table" or #(timezone.HistoricalDaylight or {}) == 0 then
		--LogDebug("[HELPERS.date:IsEnabledDateBetweenDaylightSavingTime] ---> 1 NO Existe Informacion de horario de verano en el timezone.")
		return false
	end
	local dateTime = LuaOrm.Date(dateValue):time()
	for _, info in ipairs(timezone.HistoricalDaylight) do
		--LogDebug("[HELPERS.date:IsEnabledDateBetweenDaylightSavingTime] ---> 2 dateTime: %s, Timezone: %s, info %s", dateTime, timezone.id, json.encode(info))
		if dateTime >= info.StartDayLight and dateTime <= info.EndDayLight then
			--LogDebug("[HELPERS.date:IsEnabledDateBetweenDaylightSavingTime] ---> 3 %s esta la fecha en horario de Verano. Fecha %s, Timezone: %s", info.isdst and "SIIIIIIIIII" or "NO", stringDate, timezone.id)
			return info.isdst
		end
	end
	--LogDebug("[HELPERS.date:IsEnabledDateBetweenDaylightSavingTime] ---> 4 NO esta la fecha en horario de Verano. Fecha %s, Timezone: %s", stringDate, timezone.id)
	return false
end

local function ReturnDate (date, formatDate)
	local timeStamp = date:time()
	-- si viene el formato retorna un string
	if formatDate then
		return date:toString(formatDate), timeStamp
	end
	-- si no viene el formato retorna el objeto resultante
	return date, timeStamp
end

function ConvertHourToUTCHour (self, stringHour, formatDate, timezone)
	if not stringHour then
		return nil
	end
	timezone = timezone or inconcert.authUser.timezone
	local now = LuaOrm.Date()
	local h = LuaOrm.Date( stringHour )
	local original = LuaOrm.Date {year = now:year(), month = now:month(), day = now:day(), hour = h:hour(), min = h:minute()}
	local converted = LuaOrm.Date():newFromDifferentTimezone(original:toString("%Y-%m-%d %H:%M:%S"), timezone)
	return ReturnDate( converted, formatDate )
end

function ConvertUTCHourToHour (self, stringHour, formatDate, timezone)
	if not stringHour then
		return nil
	end
	timezone = timezone or inconcert.authUser.timezone
	local now = LuaOrm.Date()
	local h = LuaOrm.Date( stringHour )
	local original = LuaOrm.Date {year = now:year(), month = now:month(), day = now:day(), hour = h:hour(), min = h:minute()}
	local converted = original:toDifferentTimezone(timezone)
	return ReturnDate( converted, formatDate )
end

--=============================================================================
--[[
	Esta función convierte a UTC la fecha que se encuentra en el timezone del Usuario.
	La misma invoca a la función "IsEnabledDateBetweenDaylightSavingTime" para determinar si debe o no ajustar la fecha resultante al Horario de Verano.
--]]
function ConvertDateToUTCDate (self, stringDate, stringHour, formatDate, isFullDate, timezone)
	-- LogDebug("[HELPERS.date:ConvertDateToUTCDate] ENTRA ---> Info: stringDate %s, stringHour: %s, formatDate %s, isFullDate: %s, timezone: %s",
	-- 	stringDate,
	-- 	stringHour,
	-- 	formatDate,
	-- 	isFullDate,
	-- 	json.encode(timezone or {})
	-- )
	if not stringDate then
		return nil
	end
	if type(stringDate) == "number" then
		local ormDate = LuaOrm.Date(stringDate)
		--LogDebug("[HELPERS.date:ConvertDateToUTCDate] --> ormDate: %s", ormDate)
		stringDate = ormDate:toString("%Y-%m-%d %H:%M:%S")
		--LogDebug("[HELPERS.date:ConvertDateToUTCDate] --> stringDate: %s", stringDate)
	end
	if not isFullDate then
		if not stringHour then
			local now = LuaOrm.Date()
			stringHour = now:toString("%H:%M:%S")
		end
		stringDate = stringDate .. " " .. stringHour
	end

	local hasChangedToDst = false
	local myTimeZone = m_table:DeepCopy(timezone or inconcert.authUser.timezone)
	if IsEnabledDateBetweenDaylightSavingTime(stringDate, myTimeZone) then
		--LogDebug("[HELPERS.date:ConvertDateToUTCDate] --> Change Timezone to Daylight Saving Time. Current date: '%s', Timezone: '%s'.", timeZoneDate, myTimeZone.id)
		myTimeZone.dst = true
		hasChangedToDst = true
	else
		myTimeZone.dst = false
	end
	local utcDate = LuaOrm.Date():newFromDifferentTimezone(stringDate, myTimeZone)

	-- LogDebug("[HELPERS.date:ConvertDateToUTCDate] SALE ---> Converted to UTC Date: timeZoneDate %s, utcDate: %s, timezone %s, formatDate: %s. %s",
	-- 	stringDate,
	-- 	utcDate,
	-- 	(myTimeZone or {}).id,
	-- 	formatDate,
	-- 	hasChangedToDst and "--> IT HAS BEEN CHANGED TO DAYLIGHT SAVING TIME" or ""
	-- )

	return ReturnDate(utcDate, formatDate)
end

--=============================================================================
--[[
	Esta función convierte al Timezone del Usuario la fecha que se encuentra en UTC.
	La misma invoca a la función "IsEnabledDateBetweenDaylightSavingTime" para determinar si debe o no ajustar la fecha resultante al Horario de Verano.
--]]
function ConvertUTCDateToDate (self, stringDate, stringHour, formatDate, isFullDate, timezone)
	-- LogDebug("[HELPERS.date:ConvertUTCDateToDate] ENTRA ---> Info: stringDate %s, stringHour: %s, formatDate %s, isFullDate: %s, timezone: %s",
	-- 	stringDate,
	-- 	stringHour,
	-- 	formatDate,
	-- 	isFullDate,
	-- 	timezone
	-- )
	if not stringDate then
		return nil
	end
	if type(stringDate) == "number" then
		local ormDate = LuaOrm.Date(stringDate)
		--LogDebug("[HELPERS.date:ConvertUTCDateToDate] --> ormDate: %s", ormDate)
		stringDate = ormDate:toString("%Y-%m-%d %H:%M:%S")
		--LogDebug("[HELPERS.date:ConvertUTCDateToDate] --> stringDate: %s", stringDate)
	end
	if not isFullDate then
		if not stringHour then
			local now = LuaOrm.Date()
			stringHour = now:toString("%H:%M:%S")
		end
		stringDate = stringDate .. " " .. stringHour
	end

	local timeZoneDate
	local hasChangedToDst = false

	local myTimeZone = m_table:DeepCopy(timezone or inconcert.authUser.timezone)
	if IsEnabledDateBetweenDaylightSavingTime(stringDate, myTimeZone) then
		--LogDebug("[HELPERS.date:ConvertUTCDateToDate] Change Timezone to Daylight Saving Time. Current date: '%s', Timezone: '%s'.", stringDate, myTimeZone.id)
		myTimeZone.dst = true
		hasChangedToDst = true
	else
		myTimeZone.dst = false
	end
	local timeZoneDate = LuaOrm.Date(stringDate):toDifferentTimezone(myTimeZone, formatDate)

	-- LogDebug("[HELPERS.date:ConvertUTCDateToDate] SALE ---> Converted to Timezone Date: utcDate %s, timeZoneDate: %s, timezone %s, formatDate: %s. %s",
	-- 	stringDate,
	-- 	timeZoneDate,
	-- 	(myTimeZone or {}).id,
	-- 	formatDate,
	-- 	hasChangedToDst and "--> IT HAS BEEN CHANGED TO DAYLIGHT SAVING TIME" or ""
	-- )

	return ReturnDate(timeZoneDate, formatDate)
end