-- This module gets the content of a specified table cell
-- Documentation: https://en.wiki.x.io/wiki/Module:Get_cell
-- Authors: Sophivorus
-- License: GNU General Public License 3 or later (http://www.gnu.org/licenses/gpl-3.0.html)
local p = {}

local WikitextParser = require( 'Module:WikitextParser' )

local function getError( key )
	local messages = {
		['page-not-found'] = 'Page not found',
		['page-not-valid'] = 'Invalid title',
		['table-not-given'] = 'No table id given',
		['table-not-found'] = 'Table not found',
		['cell-not-given'] = 'No cell reference given',
		['cell-not-valid'] = 'Invalid cell reference',
		['row-not-found'] = 'Row not found',
		['column-not-found'] = 'Column not found',
	}
	local frame = mw.getCurrentFrame()
	local message = frame.args[ key ] or messages[ key ]
	return mw.html.create( 'span' ):addClass( 'error' ):wikitext( message )
end

function p.main( frame )

	-- Get the template parameters
	local params = frame:getParent().args

	-- Get the page wikitext
	local pageTitle = mw.title.getCurrentTitle()
	local page = params[3]
	if page then pageTitle = mw.title.new( page ) end
	if not pageTitle then return getError( 'page-not-valid' ) end
	local pageWikitext = pageTitle:getContent()
	if not pageWikitext then return getError( 'page-not-found' ) end

	-- Get the table data
	local tableId = params[2]
	if not tableId then return getError( 'table-not-given' ) end
	local tableWikitext = WikitextParser.getTableById( pageWikitext, tableId )
	local tableData = WikitextParser.getTableData( tableWikitext )

	-- Replace the cell reference (A1, B2, etc) for the real value
	local cellReference = params[1]
	if not cellReference then getError( 'cell-not-given' ) end
	if not string.match( cellReference, '[A-Z]+[0-9]+' ) then getError( 'cell-not-valid' ) end
	local rowReference = string.match( cellReference, '[A-Z]+' )
	local rowNumber = string.find( 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', rowReference )
	local rowData = tableData[ rowNumber ]
	if not rowData then getError( 'row-not-found' ) end
	local columnReference = string.match( cellReference, '[0-9]+' )
	local columnNumber = tonumber( columnReference )
	local value = rowData[ columnNumber ]
	if not value then getError( 'column-not-found' ) end

	-- If the cell value is numeric, format it to simplify subsequent calculations
	local language = mw.language.getContentLanguage()
	local number = language:parseFormattedNumber( value )
	if number then return number end
	return value
end

return p