-- This module implements Template:Alhatorah. Based on Template:Bibleverse
local p = {}

--possible book inputs, based on Chicago Manual
local book_aliases = {
	['Bereshit'] = {'breishit', 'genesis', 'gen', 'gn'},
	['Shemot'] = {'exodus', 'exod', 'ex'},
	['Vayikra'] = {'leviticus', 'lev', 'lv'},
	['Bemidbar'] = {'bamidbar', 'numbers', 'num', 'nm'},
	['Devarim'] = {'deuteronomy', 'deut', 'dt'},
	['Yehoshua'] = {'joshua', 'josh' , 'jo'},
	['Shofetim'] = {'shoftim', 'judges', 'judg', 'jgs'},
	['Shemuel I']  = {'shemueli',  'shemuel1', 'shmueli',  'shmuel1', 'shmueli', '1shmuel', 'ishmuel',  '1sam', '1sm', 'isamuel'},
	['Shemuel II'] = {'shemuelii', 'shemuel2', 'shmuelii', 'shmuel2', 'shmuelii','2shmuel', 'iishmuel', '2sam', '2sm', 'iisamuel'},
	['Melakhim I']  = {'melachim1', 'melachimi',  'melakhim1', 'melakhimi',  '1kings', 'imelachim',  '1kgs','ikings'},
	['Melakhim II'] = {'melachim2', 'melachimii', 'melakhim2', 'melakhimii', '2kings', 'iimelachim', '2kgs','iikings'},
	['Yeshayahu'] = {'isaiah', 'isa', 'is'},
	['Yirmeyahu'] = {'yirmiyahu', 'jeremiah', 'jer'},
	['Yechezkel'] = {'ezekiel', 'ezek', 'ez'},
	['Hoshea'] = {'hosea', 'hos'},
	['Yoel'] = {'joel', 'jl'},
	['Amos'] = {'amos', 'am'},
	['Ovadyah'] = {'ovadiah', 'obadiah', 'obad', 'ob'},
	['Yonah'] = {'jonah', 'jon'},
	['Mikhah'] = {'michah', 'micah', 'mic', 'mi'},
	['Nachum'] = {'nahum', 'nah', 'na'},
	['Chavakkuk'] = {'habakkuk', 'hab', 'hb'},
	['Zephanyah'] = {'tzefaniah', 'zephaniah', 'zeph', 'zep'},
	['Chaggai'] = {'haggai', 'hag', 'hg'},
	['Zekharyah'] = {'zechariah', 'zech', 'zec'},
	['Malakhi'] = {'malachi', 'mal'},
	['Tehillim'] = {'psalms', 'ps', 'pss', 'psalm'},
	['Mishlei'] = {'proverbs', 'prov', 'prv'},
	['Kohelet'] = {'ecclesiastes', 'eccles', 'eccl', 'qoheleth'},
	['Shir HaShirim'] = {'shirhashirim', 'songofsolomon', 'songofsol', 'songofsongs', 'song', 'sg', 'canticles', 'canticleofcanticles'},
	['Eikhah'] = {'lamentations', 'lam'},
	['Rut'] = {'ruth', 'ru'},
	['Esther'] = {'esther', 'est'},
	['Iyyov'] = {'job', 'jb'},
	['Daniel'] = {'daniel', 'dan', 'dn'},
	['Divrei HaYamim I']  = {'divreihayamimi',  'divreihayamim1', 'ichronicles',  '1chronicles', '1chron', '1chr'},
	['Divrei HaYamim II'] = {'divreihayamimii', 'divreihayamim2', 'iichronicles', '2chronicles', '2chron', '2chr'},
	['Ezra'] = {'ezra', 'ezr'},
	['Nechemyah'] = {'nechemiah', 'nehemiah', 'neh'},
}

--these books only have one chapter, have to be handled differently
local no_chapters = {
	['obadiah'] = true,
}

local function trimArg(text)
	if type(text) == 'string' then
		text = text:match('(%S.-)%s*$')  --trimmed text or nil if empty
	end
	return text
end

local function valueExists(tbl, value)
	for _, v in pairs(tbl) do
		if value == v then
			return true
		end
	end
	return false
end

function p.main(frame)
	local targs = frame:getParent().args
	local args = {}
	for _, param in ipairs({1, 2, 3, 4, 5, 'nobook'}) do
		args[param] = trimArg(targs[param])
	end
	local input_book = ''
	local ref = ''
	local commentary = ''
	local text = ''
	local mainspace = mw.title.getCurrentTitle():inNamespaces(0)
	
	--analyze arguments
	if args[1] == nil or args[2] == nil or tonumber(args[1]) ~= nil then
		-- first argument is a numeric prefix and second is book name
		input_book = trimArg((args[1] or '') .. ' ' .. (args[2] or '')) or ''
		ref = args[3] or ''
		commentary = args[4] or ''
		text = args[5] or trimArg((input_book .. ' ' .. ref))
	else
		-- first argument is the whole book name
		input_book = args[1] or ''
		ref = args[2] or ''
		commentary = args[3] or ''
		text = args[4] or (input_book .. ' ' .. ref)
	end
	if args.nobook == 'yes' then
		text = ref
	end
	
	--analyze book (for URL)
	local book = input_book:gsub('%p', ''):gsub(' ', '_')
	book_lower = mw.ustring.lower(book)
	book_lower = book_lower:gsub('_', '')
	local book_found = false
	for full_book, aliases in pairs(book_aliases) do
		if book_lower == mw.ustring.lower(full_book:gsub(' ', '_')) or valueExists(aliases, book_lower) then
			book = full_book:gsub(' ', '_')
			book_found = true
			break
		end
	end

	--analyze verse
	local split_ref = mw.text.split(ref, '[-–—]')       --split the ref into the part before and after the dash/hyphen
	local s_ref = mw.text.split(split_ref[1], '%p')     --any punctuation can be used to separate chapter from verse
	local e_ref = split_ref[2] or split_ref[1]
	e_ref = mw.text.split(e_ref, '%p')
	for i, v in ipairs(s_ref) do s_ref[i] = v:gsub('%D', '') end  --remove any non-numeric character (such as f)
	for i, v in ipairs(e_ref) do e_ref[i] = v:gsub('%D', '') end
	local s_chap, s_vers
	local chapter_only = not s_ref[2]
	if no_chapters[book] then
		chapter_only = false
		s_chap = 1
		s_vers = s_ref[2] or s_ref[1] or 1   --verse 3 can be specified as "3" or "1:3"
	else
		s_chap = s_ref[1] or 1
		s_vers = s_ref[2] or 1
	end

	--build URL
	commentary = commentary:gsub(' ', '_') --must be outside URL command
	local urlpat = 'https://mg.alhatorah.org/Dual/_commentary/_book/_schap._svers#m7e3n7'
	local url = urlpat:gsub('_%l+', {  --get the components into the url
					_commentary = commentary,
					_book    = book,
					_schap   = s_chap,
					_svers   = s_vers,
				})

	--build text
	text = text:gsub('-', '–')  --change hyphens to en dashes (3:2-5 → 3:2–5)
	text = commentary:gsub('_', ' ') .. ', ' .. text
	
	local fulllink
	fulllink = '[' .. url .. ' ' .. text .. ']'

	if mainspace then
		if not book_found then
			table.insert(errors, '<span style="color:red">Template:Bibleverse with invalid book</span>[[Category:Pages with Bible book errors]]')
		end
		if version_num then
			table.insert(errors, '[[Category:Pages with numeric Bible version references]]')
		end
	end
	return fulllink --.. table.concat(errors)
end

return p