Dead by Daylight Wiki
Iscriviti
Advertisement

local p = {}
local utils = require("Module:Utils")
local data = require("Module:Datatable" .. utils.lang())
local perksData = mw.loadData("Module:Datatable/Perks" .. utils.lang())
local sosData = mw.loadData("Module:Datatable/SoS")
local mPerks = require("Module:Perks")
local str = require("Module:Strings")
local frame = mw.getCurrentFrame()

local _sosRefreshDate = {wday = 2, hour = 15} --UTC --wday = 1 => Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday, 7 = Sunday; "min" and "sec" are supported as well
local _inception = {year = 2016, month = 10, day = 26}
local _prices = {2000, 4000, 6000}
local _day = utils.timeContants.day --hours * minutes * seconds
local _week = utils.timeContants.week
local _sosCountTableColumns = 6
local _inceptionColor = "3bg" --clr template value
local _countOfPerksWithHigherPrice --it's set by SetGlobalCountOfPerksWithHigherPrice()

local sos = sosData.sos
local sosCount = sosData.count
local perks = perksData.perks
local perksCount = perksData.count

p.strings = {
	teachable = "Teachable", --[[File:Teachable ...]]
	
	foreignLang = false, --not used
	wrongCharType = "Error: Invalid Character Type in [[Modulo:DataTable]] in the 'Perks' Table",
	icon = "Icona",
	name = "Nome",
	weeksOf = "Settimana",
	shrineCount = "Conteggio dei Reliquiari",
	week = "Settimana",
	weeks = "settimane",
	weeksAgo = "Fa",
	weekAgoString = "#result #weekString #weeksAgo",
	--weekAgoString = "#weeksAgo #result #weekString", --example for foreign language with different wording order
	currentlyInSoS = "Attualmente nel Reliquiario dei Segreti!",
	lastOcc = "Ultima Apparizione",
	sos = "Reliquiario dei Segreti",
	
	cost = "Costo",
	IS = "Frammenti Iridescenti",
	tPerk = "Competenze Trasferibili",
	uPerkOf = "Proprietari delle Competenze",
	refreshes = "si aggiorna fra",
	minutes = "Minuti",
	hours = "Ore",
	hour = "Ora",
	days = "Giorni",
	unknownPerk = "Competenza Sconosciuta",
	unknown = "Sconosciuto",
	notImplemented = "Non Implementato",
}
local strings = p.strings
if utils.lang() ~= cstr.empty and (counter or 0) < 1 then
	counter = (counter or 0) + 1
	strings = require("Module:SoS" .. utils.lang()).strings
end

regexTable = {
	["#weeksAgo"] = strings.weeksAgo,
	["#week"] = strings.week:lower(),
	["#weeks"] = strings.weeks
}


function p.convertSoSIds() -- this is just helping function generating a SoS list increased by 32 common and unused perks (it's not used in any other function)
	local modulePerks = require("Module:Perks")
	local result = {}
	for _, week in ipairs(sos) do
			local newWeek = {}
		for i = 1, 4, 1 do
			table.insert(newWeek, week[i] + modulePerks._nonUniquePerksCount)
		end
		table.insert(result, newWeek)
	end
	for _, week in ipairs(result) do
		mw.log("{" .. week[1] .. ", " .. week[2] .. ", " .. week[3] .. ", " .. week[4] .. "},")
	end
end

--------------------------------------------------------------------------------------------------------
								-- SoS Version 2.0 since patch 6.1.0 --
--------------------------------------------------------------------------------------------------------
function p.SoS2(index)
	return p.assembleSoS2(GetSoSPerks(sos[sosCount - tonumber(index.args[1])]))
end

function SoS2(index, showTimer, parameters)
	return p.assembleSoS2(GetSoSPerks(sos[index]), showTimer, parameters)
end

function p.CurrentSoS2()
	return p.assembleSoS2(GetSoSPerks(sos[1]), true, sos[1][5]) --table after ID quartet
end

function p.ManualSoS2(args) --Used in Documentation
	return p.assembleSoS2(GetSoSPerks(args.args))
end

function p.assembleSoS2(sosPerks, showCountdown, parameters)
	showCountdown = showCountdown or false
	parameters = parameters or false
	local result = cstr.empty
	local timer = parameters and parameters.timer or 0
	local costModifier = parameters and parameters.cost or 0
	
	for i, perk in ipairs(sosPerks) do
		local perkOwner = mPerks.getPerkOwnerByPerk(perk)
		local ownerName = (perkOwner and utils.resolveCharacterIconLinkName(perkOwner)) or cstr.empty
		local perkName = utils.GetDisplayName(perk)
		local perkImage = utils.assembleImage("sosPerk", perkName)
		result = result .. nl ..
			'<div class = "sosPerk sosPerk' .. i .. '">' .. nl ..
				perkImage .. nl ..
				'<div class = "sosPerkDesc sosPerkDesc' .. i .. '">' .. nl ..
					'<div class = "sosPerkDescName' .. (#perkName > 20 and space ..'smallerText' or cstr.empty) .. '">' .. perkName .. '</div>' .. nl ..
					'<div class = "sosPerkDescDivider"><hr style = "margin: 0px"></div>' .. nl ..
					((perkOwner and '<div class = "sosPerkOwner">' .. (utils.isKiller(perkOwner) and utils.replaceLastSpaceByNBSP(the(perkOwner)) or cstr.empty) .. utils.IconLink(ownerName, ownerName, perkOwner.name) .. '</div>') or cstr.empty) ..
		    	'</div>' .. nl ..
			'</div>'
	end
	
	result =
		thLine(class('sosHeader') .. 'width = "256px" colspan = 4', strings.sos) ..
		tLine('colspan = 4', '<div class = "sos2">'.. result .. '</div>') ..
		thLine('height = 128px', strings.cost) ..
		hl .. class('BG-All', 'PerkCostsBG', 'SquareBG-2-enh') .. tl .. utils.formatNum(p.getAdjustedPerkCost(_prices[1], costModifier), 0) .. br .. file('IconHelp_iridescentShards.png', '56px', 'link=' ..strings.IS) .. nl ..
		hl .. class('BG-All', 'PerkCostsBG', 'SquareBG-3-enh') .. tl .. utils.formatNum(p.getAdjustedPerkCost(_prices[2], costModifier), 0) .. br .. file('IconHelp_iridescentShards.png', '56px', 'link=' ..strings.IS) .. nl ..
		hl .. class('BG-All', 'PerkCostsBG', 'SquareBG-4-enh') .. tl .. utils.formatNum(p.getAdjustedPerkCost(_prices[3], costModifier), 0) .. br .. file('IconHelp_iridescentShards.png', '56px', 'link=' ..strings.IS) .. nl ..
		((showCountdown and thLine(class('sosHeader') .. 'colspan = 4', strings.refreshes .. space .. clr(4, p.GetSoSRemainingTime(timer)))) or cstr.empty)
	
	result = utils.wrapTable(result, "sosTable disableTooltip", nil, true)
	
	mw.log(result)
	return result
end

--------------------------------------------------------------------------------------------------------
							-- SoS Version 2.0 since patch 6.1.0 END --
--------------------------------------------------------------------------------------------------------


-- Assembling SoS Table --

function p.getAdjustedPerkCost(price, modifier)
	if modifier >= -1 and modifier <= 1 then --then it's a percentage sale
		return price * (modifier + 1) -- ( -0.25 + 1 => 75% )
	else
		return price + modifier
	end
end

function p.GetSoSRemainingTime(timer) --updated to SoS2
	timer = timer or 0
	local result = cstr.empty
	local SoSRefreshDate = _sosRefreshDate
	local currentTime = utils.GetDatetime(utils.today())
	local remainingDays = SoSRefreshDate.wday + 7 - currentTime.wday --7 days is week days constant
	lg(remainingDays)
	--local nextWeek = remainingDays > 7
	remainingDays = (SoSRefreshDate.hour and remainingDays == 7 and currentTime.hour < SoSRefreshDate.hour and 0) or 
		(remainingDays > 7 and remainingDays % 7) or remainingDays --if the result is bigger than 7 it means it will be next week and needs to be lowered
	
	local nextRefresh = utils.GetDatetime(utils.addTime("day", remainingDays, currentTime.timestamp))
	nextRefresh.hour = SoSRefreshDate.hour or 0 --set time as per Constant SoSRefreshDate
	nextRefresh.min = SoSRefreshDate.min or 0
	nextRefresh.sec = SoSRefreshDate.sec or 0
	nextRefresh.timestamp = utils.toTimestamp(nextRefresh) --timestamp needs to be updated based on new time values

	local remainingTime = utils.getTimeDiff(currentTime.timestamp, nextRefresh.timestamp) --in seconds
	local rtTable = utils.GetDatetime(remainingTime, true) --remainingTime as a table
	dmp(rtTable)
	if(timer == 24) then
		remainingTime = rtTable.timestamp - utils.addTime("day", rtTable.day)
		rtTable = utils.GetDatetime(remainingTime, true)
	end
	
	--last 24 hour
	if rtTable.day == 0 then
	   --last hour
		if rtTable.hour == 0 then
			result = math.ceil(utils.getTimeDiffFormatting(remainingTime, "minute")) .. space .. strings.minutes
		else
			result = math.ceil(utils.getTimeDiffFormatting(remainingTime, "hour")) .. space .. strings.hours
		end
	else
		--More than 24 hour
		result = math.ceil(utils.getTimeDiffFormatting(remainingTime, "day")) .. space ..  strings.days
	end

	mw.log(result)
	return result
end

function GetSoSPerkImageByPerk(perk)
	if perk == 0 then return "Dbd-perks-template.png" end
	local name = utils.FirstLetterLower(utils.resolveFileName((perk.techName or perk.name), false))
	return strings.teachable .. "_" .. name .. dot .. cstr.png
end

function GetSoSPerks(sos)
	local result = {}

	for i, perkId in ipairs(sos) do --this form should prevent to to fial due to metadata table in args table when the args table is passed
		local perk = mPerks.getPerkById(tonumber(perkId))
		if perk ~= nil then
			table.insert(result, perk)
		end
	end

	--mw.log(mw.dumpObject(result))
	return result
end

function SetGlobalCountOfPerksWithHigherPrice()
	for _,dlc in ipairs(data.dlcs) do
		if not utils.IsFullDateTime(dlc.rDate) then
			_countOfPerksWithHigherPrice = 24
			return 24
		end
	end
	_countOfPerksWithHigherPrice = 18
	return 18
end

-- #END# Assembling SoS Table #END# --

--ISO: https://en.wikipedia.org/wiki/ISO_week_date
--If 1 January is on a Monday, Tuesday, Wednesday or Thursday, it is in W01. If it is on a Friday, it is part of W53 of the previous year.
--If it is on a Saturday, it is part of the last week of the previous year which is numbered W52 in a common year and W53 in a leap year.
--If it is on a Sunday, it is part of W52 of the previous year.
function GetWeekNumber(dateStamp) --in milliseconds, os.time()
	firstWeekDayOfYear = tonumber(os.date("%w", os.time({year = os.date("%Y", dateStamp), month = 1, day = 1})))
	firstWeekOfYear = tonumber(os.date("%W", os.time({year = os.date("%Y", dateStamp), month = 1, day = 1})))
	
	-- ATTENTION as per description above some years have first week 01
	-- because all first weeks of year that starts with Sunday, Saturday, Friday or Thursday must be shifted
	if firstWeekDayOfYear > 0 and firstWeekDayOfYear < 4  and firstWeekOfYear == 0 then
		return tonumber(os.date("%W", dateStamp)) + 1
	else
		return tonumber(os.date("%W", dateStamp))
	end
end

function p.GetCurrentWeekNumber()
	return GetWeekNumber(os.time())
end

function GetEmptyPerkTable()
	local result = {}
	for i = 1, perksCount do result[i] = 0 end  --make empty table with 0 values for every perk in sos table
	--else for i = 1, #perks do result[i] = {} end end --not used?
	return result
end

function GetCountOfPerks()
	local perkList = GetEmptyPerkTable()

	for i, sosWeek in ipairs(sos) do
		for j, sosPerk in ipairs(sosWeek) do
			if type(sosPerk) ~= "table" and sosPerk > 0 then
				--mw.logObject("sosPerk: " .. sosPerk)
				if perkList[sosPerk] == 0 then --sosPerk, the perk ID will be an index of perkList table. Due to Lua logic there must not be a nil between items (that's why there is getEmptyPerkTable())
					perkList[sosPerk] = 1 --DEV TODO check if possible to remove it
				else
					perkList[sosPerk] = perkList[sosPerk] + 1
				end
			end
		end
	end
	return perkList
end

function p.AssembleSoSPerkCountTable()
	local SoSPerkCountTable = GetCountOfPerks()
	local maxOccurrence = math.max(unpack(SoSPerkCountTable))
	local result = cstr.empty
	local number
	utils.sortItemsByName(perks)

	local i = 1
	for _, perk in ipairs(perks) do
		if perk.character ~= nil and not perk.retired then
			if (i - 1) % _sosCountTableColumns == 0 then
				result = result .. ntl .. nl
			end
			number = SoSPerkCountTable[perk.id]
			result = result .. 
				hl .. utils.assembleImage("sosPerk", utils.GetDisplayName(perk), 64) .. nl .. 
				hl .. link(perk.name) .. nl
			if number ~= 0 then
				result = result .. "<div class='noticeText' title='" .. GetTextWeeksAgoOfLastOccurrenceById(perk.id) .. "'>" .. strings.lastOcc .. colon .. space .. GetLastPerkOccurrenceById(perk.id) .. "</div>" .. nl
			end
			result = result .. tl .. center(b(GetColoredOccurrenceNumber(number, maxOccurrence))) .. nl
			
			i = i + 1
		end
	end
	result = utils.wrapBasicTable(result, "unsortable")
	
	return result
end

function GetColoredOccurrenceNumber(number, maxOccurrence)
	if		number == maxOccurrence	then return clr(3, number)
	elseif	number == 0 			then return clr(8, number)
	elseif	number == 1 			then return clr(2, number)
	elseif	number == nil			then return strings.unknown
	end
	return number
end

--Old ID is the ID that occurs in old Perk table in Datatable (not in Datatable/Perks)
function GetWeeksAgoOfLastOccurrenceById(id)
	local offset = 0

	for i, sosWeek in ipairs(sos) do -- i = weeks ago (to current day)
		--mw.log(mw.dumpObject(sosWeek))
		for j, perk in ipairs(sosWeek) do
			if j <= 4 then
				if perk == id then
					--mw.log("Last Occ.: " .. GetDateFromSoSIndex(i + offset) .. ", Perk: " .. mPerks.getPerkById(id).name)
					return i - 1 + offset
				end
			else
				if perk.offset ~= nil then
					offset = offset + perk.offset
				end
			end
		end
	end
	return 0
end

function GetLastPerkOccurrenceById(id)
	return GetDateFromSoSIndex(GetWeeksAgoOfLastOccurrenceById(id))
end

--sosIndex should be a number of how many weeks ago the perk occurred
function GetDateFromSoSIndex(sosIndex)
	local result = os.time() - sosIndex * _week
	local weekDay =  tonumber(os.date("%w", result))
	local offset
	
	if weekDay < 3 then offset = (-weekDay - 4) * _day -- current day is Sunday, Monday, or Tuesday (WeekDay = 0 - 2)
	elseif weekDay > 3 then offset = (-weekDay + 3) * _day --current day is Thursday, Friday, or Saturday (WeekDay = 4 - 6)
	else offset = 0	end -- current day is Wednesday
	
	return os.date("%d.%m.%Y", result + offset) --offset is in negative
	--2 = -6
	--1 = -5
	--0 = -4
	--6 = -3
	--5 = -2
	--4 = -1
	--3 =  0
end

function GetTextWeeksAgoOfLastOccurrenceById(id) --there will be probably needed to make a copy of a replacing string
	result =  GetWeeksAgoOfLastOccurrenceById(id)
	if result > 1 then
		strings.weekAgoString = strings.weekAgoString:gsub("#weekString", "#weeks")
	elseif result == 1 then
		strings.weekAgoString = strings.weekAgoString:gsub("#weekString", "#week")
	else
		return strings.currentlyInSoS
	end
	
	return utils.regularReplace(strings.weekAgoString:gsub("#result", result), regexTable)
end

function GetIndexesOfPeriod(year)
	year = tonumber(year)
	local currentWeekDate = os.time(_inception)
	local currentYear
	local index = sosCount
	local result = {}

	
	for i, sosWeek in ipairs(sos) do
		currentYear = tonumber(os.date("%Y", currentWeekDate))
		--mw.log("current Year: " .. currentYear .. ", i: " .. i .. ", index: " .. index .. "sos: {" .. (sos[index][1] ~= nil and (sos[index][1] .. ", " .. sos[index][2] .. ", " .. sos [index][3] .. ", " ..sos[index][4]) or "NULL, NULL, NULL, NULL") .. "}") -- sos[index][1] .. ", " .. sos[index][2] .. ", " .. sos [index][3] .. ", " ..sos[index][4]
		if year == nil or year == currentYear then
			if result[1] == nil then 
				result[1] = index
			end
			--mw.log("[" .. index .. "] Week " ..GetWeekNumber(currentWeekDate) .. ", Year: " .. os.date("%Y", currentWeekDate) .. ": {" .. sos[index][1] .. ", " .. sos[index][2] .. ", " .. sos[index][3] .. ", " .. sos[index][4] .. "} (" .. os.date("%d. %m. %Y",currentWeekDate) .. ")")
			result[2] = index
		end
		
		-------------------------------
		index = sosCount - i -- INDEX SHIFT
		if sos[index] ~= nil and sos[index][5] ~= nil and sos[index][5].offset ~= nil then --need to reorder logic instructions
			currentWeekDate = currentWeekDate + (_week * (sos[index][5].offset + 1))
		else
			currentWeekDate = currentWeekDate + _week
		end
	end
	--mw.log(mw.dumpObject(result))
	if #result == 0 then return {0, 0} end --if pStart and pEnd is nil then return zero values
	return result
end

function ResolveYearParam(year)
	if type(year) == "table" and year.args[1] ~= nil then
		return tonumber(year.args[1])
	elseif type(year) == "number" then
		return year
	else
		return tonumber(os.date("%Y"))
	end
end

function SoSArchiveCalendar(year, pStart, pEnd)
	local currentWeekDate = os.time(_inception)
	local perkList = GetEmptyPerkTable()
	if pStart == nil or pEnd == nil then
		pStart, pEnd = unpack(GetIndexesOfPeriod(year)) --Period Start and Period End
	end
	local offset = 0
	local offset2016 = 0
	local notices = {}
	local week, color, index, text, header
	
	if year == 2016 then
		offset2016 = tonumber(os.date("%W", os.time(_inception))) - 1 --setting offset by 43 weeks
	end
	
	for i = pStart, pEnd, -1 do
		week = (pStart - i + 1 + offset2016)
		if sos[i][5] ~= nil and type(sos[i][5]) == types.table then
			offset = offset + (sos[i][5].offset or 0) --offset must be global because we need to shift the rest of all weeks as well
			color  = sos[i][5].color
			notices[week] = sos[i][5].notice
			text = sos[i][5].text
			header = sos[i][5].header
		else
			color = nil
			header = nil
		end
		for j, sosPerk in ipairs(sos[i]) do --sosPerk = individual perk in sos Week row, goes 4x - 5x
			if type(sosPerk) ~= types.table then
				if sosPerk ~= 0 then
					local occurenceIndex
					if perkList[sosPerk] == 0 then --sosPerk, the perk ID will be an index of perkList table. Due to Lua logic there must not be a nil between items (that's why there is getEmptyPerkTable())
						occurenceIndex = 1
						perkList[sosPerk] = {}
					else
						occurenceIndex = #perkList[sosPerk] + 1
					end
					
					local newOccurence = { --here insert data you want to be accessible while creating a calendar (+ initialize the variable above (#413))
						week = week + offset,
						color = color,
						text = text,
						header = header
					}
					
					perkList[sosPerk][occurenceIndex] = newOccurence
				end
			end
		end
	end
	return {perkList, notices} -- sorting: perkList[perks.id] gives you weeks of appropriate perk
end

function GetGlobalOffsetInYear(pStart, pEnd)
	local offset = 0
	for i = pStart, pEnd, -1 do
		if sos[i][5] ~= nil and type(sos[i][5]) == "table" then
			offset = offset + (sos[i][5].offset or 0)
		end
	end
	mw.log("Week Offset: " .. offset)
	return tonumber(offset)
end

function GetPerksInception(year)
	local dlcs = require("Module:DLCs" .. utils.lang())
	local charTable
	local dlcDate
	local weekOffset
	local result = GetEmptyPerkTable()
	for i, perk in ipairs(perks) do
		if perk.character ~= nil then --if Perk has associated character that means it's a unique perk
			if		perk.charType == 'S' then charTable = survivors
			elseif	perk.charType == 'K' then charTable = killers
			else	return -1
			end
			if charTable[perk.character].dlc ~= nil then
				local dlc = dlcs.getCharacterMainDlc(charTable[perk.character])
				dlcDate = utils.GetDatetime(dlc.rDate)
				if tonumber(year) == tonumber(dlcDate.year) then
					weekOffset = tonumber(os.date("%W", os.time({year = dlcDate.year, month = 1, day = 1}))) --check if the year starts with W0 or W1 - see #48 (documentation of GetWeekNumber())
					releaseWeek = tonumber(os.date("%W", os.time(dlcDate))) - weekOffset + 1 -- +1 because week indexing start at 0
					
					result[perk.id] = {week = releaseWeek, color = _inceptionColor, inception = true}
						
					--mw.log("Perk " .. perk.name .. " was released at week " .. releaseWeek .. "(+" .. weekOffset .. ")")
				end
			end
		end
	end
	return result
end

function mergePerkListWithInceptionList(perkList, perkInception)
	local merged = GetEmptyPerkTable()
	
	for i = 1, #perkList do --perkList as I would to keep dependency on the logic that's used when creating perkList variable due to potential later changes
		if perkInception[i] ~= 0 then
			if perkList[i] == 0 then
				perkList[i] = {perkInception[i]}
			else
				perkList[i][#perkList[i] + 1] = perkInception[i]
			end
		end
	end
	
	--mw.log(mw.dumpObject(perkList))
	return perkList
end

function ResolvePerkOccurence(perkOccurenceList)
	local result = 0
	for _, perkOcc in ipairs(perkOccurenceList) do
		if perkOcc.inception == true then
		else
			result = result + 1
		end
	end
	return result
end

function p.AssembleSoSCalendarTable(year)
	year = ResolveYearParam(year)
	local pStart, pEnd = unpack(GetIndexesOfPeriod(year))
	local perkList, weekNames = unpack(SoSArchiveCalendar(year, pStart, pEnd))
	local perkInception = GetPerksInception(year)
	local result = cstr.empty
	local currentWeekDate = 1
	local startWeekDate = 1
	local weekFound
	local hideable
	if year == 2016 then
		currentWeekDate = tonumber(os.date("%W", os.time(_inception)))
		startWeekDate = tonumber(os.date("%W", os.time(_inception)))
	end
	local globalOffset = GetGlobalOffsetInYear(pStart, pEnd)
	local lastWeekNumber = currentWeekDate + (pStart - pEnd + globalOffset)
	local numberOfWeeksInYear = pStart - pEnd + 1 + globalOffset
	
	if perkInception == -1 then return strings.wrongCharType end
	perkList = mergePerkListWithInceptionList(perkList, perkInception)
	
	result = result .. 
		'<div id=' .. quotes("inceptionPerks" .. year) .. space .. class("inceptionSwitch") .. '></div>' .. nl .. --Show/Hide Switch
		'{| class="wikitable unsortable"' .. nl ..
		hl .. strings.icon .. dhl .. strings.name .. dhl .. "colspan = " .. numberOfWeeksInYear .. tl .. strings.weeksOf .. space .. year .. dhl .. strings.shrineCount .. nl .. ntl .. nl ..
		hl .."colspan = 2" .. tl .. nl
	--mw.log(mw.dumpObject(weekNames))
	
	for i = 1, numberOfWeeksInYear do -- Weeks Header
		if i ~= 1 then
			result = result .. dtl .. class("week-cell") .. tl
		else
			result = result .. tl .. class("week-cell") .. tl
		end
		result = result ..  (weekNames[currentWeekDate] or currentWeekDate)
		currentWeekDate = currentWeekDate + 1
	end
	result = result .. nl .. hl .. nl
	
	utils.sortItemsByName(perks)
	--mw.log("pStart: " .. pStart)
	--mw.log("pEnd: " .. pEnd)
	--mw.log("Number of Weeks (without weeks with offsets): " .. numberOfWeeksInYear)
	--mw.log(mw.dumpObject(sos[pStart]))
	--mw.log(mw.dumpObject(sos[pEnd]))
	--mw.log(lastWeekNumber)
	--mw.log(lastWeekNumber - (pStart - pEnd))
	mw.log(mw.dumpObject(perkList))
	for i, perk in ipairs(perks) do
		if perk.character ~= nil and perkList[perk.id] ~= 0 then
			for j, perkOcc in ipairs(perkList[perk.id]) do
				hideable = false
				if perkOcc.inception == true and (j == 1 and #perkList[perk.id] == 1) then
					hideable = true
					break
				end
			end
			result = result .. ntl
			if hideable then
				result = result .. class("inception-row" .. year) .. 'style="display: none;" ' 
			end
			result = result .. nl .. hl .. utils.assembleImage("sosPerk", utils.GetDisplayName(perk), 32) .. nl .. hl .. perk.name .. nl .. tl
			
			for j = startWeekDate, lastWeekNumber do --going through weeks in year
				--j = week currently processed
				weekFound = false
				local titleText = cstr.empty
				local color = "white"
				local sameWeekCounter = 0
				for k, perkOcc in ipairs(perkList[perk.id]) do --perkOcc = Perk Occurrence
					--if perk.id == 63 and j == perkOcc.week then mw.log("Perk " .. perk.name .. ": " .. perk.id .. ", weekOcc:" .. perkOcc.week .. ", j: " .. j .. ", Text: " .. (perkOcc.text or "") .. "\n*****\n" .. mw.dumpObject(perkList[63]) .. "\n*****\n") end
					if perkOcc.week == j and not weekFound then
						sameWeekCounter = sameWeekCounter + 1
						color = (perkOcc.color or "white")
						titleText = strings.week .. space .. perkOcc.week
						if perkOcc.header then
							titleText =  titleText .. " - " .. perkOcc.header
						end
						weekFound = true
						if perkOcc.inception then break end
					elseif perkOcc.week == j and weekFound then
						if not perkOcc.inception then
							sameWeekCounter = sameWeekCounter + 1
							titleText = titleText .. "&#010;" .. strings.week .. " " .. perkOcc.week
							if perkOcc.header then
								titleText = titleText .. " - " .. perkOcc.header
							end
						else
							color = perkOcc.color
						end
					end
				end
				color = clr(color)
				
				if weekFound then
					local classes = cstr.empty
					result = result .. ' style=' .. quotes("background-color: #" .. color .. ';')
					
					if sameWeekCounter > 1 then
						classes = class("multipleOccurenceSoSCalendar")
					else
						sameWeekCounter = cstr.empty	
					end
					result = result .. classes .. ' title = ' .. quotes(titleText) .. tl .. sameWeekCounter --[[File:nothing.png]]
				end
				
				if j ~= lastWeekNumber then --if it's not occurence in last week then add delimeters
					result = result .. space ..dtl
				end
			end
			result = result .. nl .. hl .. space .. ResolvePerkOccurence(perkList[perks[i].id]) .. nl
		end
	end
	
	result = result .. "|}"
	
	--mw.log(result)
	return result
end

function p.AssembleSoSYearPage(year)
	year = ResolveYearParam(year)
	local pStart, pEnd = unpack(GetIndexesOfPeriod(year))
	local result = cstr.empty
	local currentWeekDate = 1
	local startWeekDate = 1
	local sosIndex = 0
	local header
	if year == 2016 then
		currentWeekDate = tonumber(os.date("%W", os.time(_inception))) --43
		startWeekDate = tonumber(os.date("%W", os.time(_inception))) --52
	end
	local currentOffset = 0
	local lastWeekNumber = currentWeekDate + (pStart - pEnd)

	if perkInception == -1 then return strings.wrongCharType end
	
	utils.sortItemsByName(perks)
	mw.log("pStart: " .. pStart)
	mw.log("pEnd: " .. pEnd)
	mw.log("lastWeekNumber: " .. lastWeekNumber)
	mw.log("lastWeekNumber CALC: " .. lastWeekNumber - (pStart - pEnd))
	mw.log("startWeekDate: " .. startWeekDate)
	for i = startWeekDate, lastWeekNumber do --going through week in year
		sosIndex = pStart + startWeekDate - i
		-- do return end
		if sosIndex > sosCount or sosIndex < 1 then break end --If the index is actually higher than the number of elements in SoS table or the index is below 0
		if sos[sosIndex][5] ~= nil then --If there's a table after 4 perks then retrieve data
			if sos[sosIndex][5].offset ~= nil then
				currentOffset = currentOffset + sos[sosIndex][5].offset --the number itself is a negative value, thus a +
			end
			
			if sos[sosIndex][5].header ~= nil then
				header = sos[sosIndex][5].header
			else
				header = strings.week .. space .. (i + currentOffset)
			end
			
			text = sos[sosIndex][5].text or cstr.empty
		else
			header = strings.week .. space .. (i + currentOffset)
			text = cstr.empty
		end
		--result = sos[sosIndex][1] .. ", " .. sos[sosIndex][2] .. ", " .. sos[sosIndex][3] .. ", " .. sos[sosIndex][4] .. nl .. nl .. result
		--result = ("i: " .. i .. "| Index: " .. sosIndex .. "| lastWeekNumber - currentOffset: " .. lastWeekNumber - currentOffset) .. nl .. result
		result = SoS2(sosIndex, false, sos[sosIndex][5]) .. nl .. nl .. result
		result = text .. nl .. result
		result = "== " .. header .. " ==" ..nl .. result

	end
	
	mw.log(result)
	return result
end

return p
Advertisement