มอดูล:Holiday

จากวิกิพีเดีย สารานุกรมเสรี
Documentation icon คู่มือการใช้งานมอดูล[สร้าง]
local p = {}

function p.main(frame)
	year, month, day = mw.language.new('th'):formatDate('Y n j', t, true):match('(%S-) (%S-) (%S*)')
	curtime = {year = year, month = month, day = day}
	
	months = {
		['ม.ค.'] = 1,
		['ก.พ.'] = 2,
		['มี.ค.'] = 3,
		['เม.ย.'] = 4,
		['พ.ค.'] = 5,
		['มิ.ย.'] = 6,
		['ก.ค.'] = 7,
		['ส.ค.'] = 8,
		['ก.ย.'] = 9,
		['ต.ค.'] = 10,
		['พ.ย.'] = 11,
		['ธ.ค.'] = 12
	}
	
	dates = {}
	content = mw.title.new('แม่แบบ:วันสำคัญ'):getContent():gsub('<!%-%-.-%-%->', '')
	
	for day_s, month_s, events in content:gmatch('* %[%[(%S-) (%S-)%]%] : (.-)\n') do
		month = months[month_s]
		day = tonumber(day_s)
		
		for item in events:gmatch('%s*([^,]+)') do
			item = '* [[' .. day_s .. ']] [[' .. month_s .. ']] : ' .. item:gsub('%s*%{%[%[.*', '')
			yr = item:match('%{%[%[พ%.ศ%. (%d+)%]%]%}')
			if not yr then
				yr_list = {curtime.year - 1, curtime.year, curtime.year + 1}
			else
				yr_list = {yr - 543} -- convert Thai solar year to CE
			end
			
			for i = 1, #yr_list do
				table.insert(dates, {os.time({year = yr_list[i], month = month, day = day}), item})
			end
		end
	end
	
	function cmp(a, b)
		return a[1] < b[1]
	end
	
	table.sort(dates, cmp)
	
	pre = {}
	post = {}
	
	now = os.time(curtime)
	
	for i = 1, #dates do
		if dates[i][1] >= now then
			if #post < 3 then
				table.insert(post, dates[i][2])
			else
				break
			end
		end
	end

	for i = #dates, 1, -1 do
		if dates[i][1] < now then
			if #pre < 3 then
				table.insert(pre, dates[i][2])
			else
				break
			end
		end
	end

	-- flip the array
	tmp = {}
	for i = #pre, 1, -1 do
		table.insert(tmp, pre[i])
	end
	pre = tmp
	
	return ('==== วันสำคัญที่ผ่านมา ====\n' ..
			table.concat(pre, '\n') .. '\n' ..
			'==== วันสำคัญที่กำลังจะมาถึง ====\n' ..
			table.concat(post, '\n') .. '\n')
end

return p