Documentation for this module may be created at Module:Item/doc

local p = {}

p.cleanFilename = function ( frame )
	if string.lower( string.sub( frame.args.filename, 1, 4 ) ) == 'file' then
		return string.sub( frame.args.filename, 6 )
	end
	return frame.args.filename
end

-- =p.formatDate('2025-01-01')
p.formatDate = function ( value, precision )
	if value == nil or value == '' then
		return 'undated'
	end
	local lang = mw.language.getContentLanguage()
	local timestamp = string.sub( lang:formatDate( 'YmU', value ), 7 )
	-- Format.
    local format = '[[Y]] F j D'
    if precision == 'month' then
        format = 'F [[Y]]'
    elseif precision == 'year' then
        format = '[[Y]]'
    elseif precision == 'circa' then
        format = '\\c. [[Y]]'
    elseif precision == 'decade' then
        format = '[[Y]]\\s'
    end
	return lang:formatDate( format, '@' .. timestamp )
end

p.cite = function ( frame )
	if frame.args[1] == nil and frame.args[1] == '' then
		return '<span class="error">Please set param 1 to the item code.</span>'
	end
	local id = mw.text.trim( frame.args[1] )
	local args = { where = '_pageName = "' .. id .. '"', limit = 1 }
	local results = mw.ext.cargo.query( 'items', '_pageName, title, date, date_precision', args )
	if results[ 1 ] then
		local item = results[ 1 ]
		local date = p.formatDate( item.date, item.date_precision or nil )
		return item._pageName .. ': [[' .. item._pageName .. '|' .. item.title .. ']] (' .. date .. ')'
	else
		return '<span class="error">Item "[[' .. id .. ']]" not found.</span>'
	end
end

p.main = function ( frame )
	-- Title.
	local title = '(Untitled)'
	if frame.args.title ~= nil and frame.args.title ~= '' then
		title = frame.args.title
	end

	-- Parent item.
	local parentItem = ''
	local parentItemLink = ''
	if frame.args.parent_item ~= nil and frame.args.parent_item ~= '' then
		parentItem = frame.args.parent_item
		parentItemLink = '[[' .. parentItem .. ']]'
		local args = { where = '_pageName = "' .. parentItem .. '"', limit = 1 }
		local results = mw.ext.cargo.query( 'items', 'title', args )
		if results[ 1 ] then
			parentItemLink = '[[' .. parentItem .. '|' .. parentItem .. ': ' .. results[ 1 ].title .. ']]'
		end
		parentItemLink = '<span class="mdl-item-parentItem">' .. parentItemLink .. '</span>'
	end

	-- Description.
	local description = ''
	if frame.args.description ~= nil and frame.args.description ~= '' then
		description = frame.args.description
	end
	
	-- Storage location.
	local storageLocation = ''
	local storageLocationLink = ''
	if frame.args.storage_location ~= nil and frame.args.storage_location ~= '' then
		storageLocation = frame.args.storage_location
		storageLocationLink = '<span class="mdl-item-storage-location">[[' .. storageLocation .. ']]</span>'
	end

	-- Image.
	local image = ''
	if frame.args.image ~= nil and frame.args.image ~= '' then
		image = p.cleanFilename( { args = { filename = frame.args.image } } )
	end

	-- Dates.
	local date = ''
	if frame.args.date ~= nil and frame.args.date ~= '' then
		date = frame.args.date;
	end
	local datePrecision = ''
	if frame.args.date_precision ~= nil and frame.args.date_precision ~= '' then
		datePrecision = frame.args.date_precision;
	end
	local endDate = ''
	if frame.args.end_date ~= nil and frame.args.end_date ~= '' then
		endDate = frame.args.end_date;
	end
	local endDatePrecision = ''
	if frame.args.end_date_precision ~= nil and frame.args.end_date_precision ~= '' then
		endDatePrecision = frame.args.end_date_precision;
	end
	local datesLabel = 'Date'
	local dateDisplay = p.formatDate( date, frame.args.date_precision or nil )
	if date ~= '' and endDate ~= '' then
		datesLabel = 'Date range'
		dateDisplay = dateDisplay .. ' &ndash; ' .. p.formatDate( endDate, endDatePrecision )
	end

	-- Tags.
	local tags = ''
	if frame.args.tags ~= nil and frame.args.tags ~= '' then
		tags = '[[' .. table.concat( mw.text.split( frame.args.tags, ';' ), ']]; [[' ) .. ']]';
	end

	-- Other files.
	local files = ''
	if frame.args.files ~= nil and frame.args.files ~= '' then
		local filesDiv = mw.html.create( 'div' )
		filesDiv:attr( 'class', 'mdl-item-files' )
		filesDiv:wikitext( frame.args.files )
		files = tostring( filesDiv )
	end

	-- Store Cargo data.
	if mw.title.getCurrentTitle():inNamespace( 0 ) then
		mw.ext.cargo.store( 'items', {
			title              = title,
			parent_item        = parentItem,
			description        = description,
			image              = image,
			date               = date,
			date_precision     = datePrecision,
			end_date           = endDate,
			end_date_precision = endDatePrecision,
			storage_location   = storageLocation
		} )
	end
	
	-- Main item wikitext output.
	local out = ''
	if image ~= '' then
		out = out .. '[[File:' .. image .. '|300px|right]]'
	end
	local url = mw.title.getCurrentTitle():canonicalUrl()
	local qrcode = mw.getCurrentFrame():callParserFunction( '#qrlite', { url, format = 'png', size = '4' } )
	out = out .. '<div class="mdl-item-qrcode">' .. qrcode .. '</div>\nItem details:\n\n'
		.. '* <strong>Parent item:</strong> ' .. parentItemLink .. '\n'
		.. '* <strong>Title:</strong> ' .. title .. '\n'
		.. '* <strong>' .. datesLabel .. ':</strong> ' .. dateDisplay .. '\n'
		.. '* <strong>Tags:</strong> ' .. tags .. '\n'
		.. '* <strong>Storage location:</strong> ' .. storageLocationLink .. '\n'
		.. '* <strong>Description:</strong><div>\n' .. description .. '</div>\n'

	if files ~= '' then
		out = out .. '== Attached files ==\n' .. files .. '\n'
	end

	-- Child items (the current_title arg is for testing puposes).
	local currentTitle = nil
	if frame.args.current_title ~= nil and frame.args.current_title ~= '' then
		currentTitle = frame.args.current_title
	elseif mw.title.getCurrentTitle() then
		currentTitle = mw.title.getCurrentTitle().text
	end
	if currentTitle ~= nil then
		local args = {
			where = 'parent_item = "' .. currentTitle .. '"',
			orderBy = 'date ASC'
		}
		local childItemsResults = mw.ext.cargo.query( 'items', '_pageName, title, description, date, storage_location', args )
		if #childItemsResults > 0 then
	        out = out .. '== Items ==\nThe following items are part of this one.\n{|class="wikitable sortable"\n'
		end
		for r = 1, #childItemsResults do
	        local childItem = childItemsResults[r]
	        out = out .. '|-\n| ' .. ( childItem.date or '<em>Undated</em>' )
	        	.. ' || [[' .. childItem._pageName .. ']]'
	        	.. ' || ' .. childItem.title
	        	.. ' || ' .. childItem.description .. '\n'
	        	.. ' || ' .. childItem.storage_location .. '\n'
		end
    	if #childItemsResults > 0 then
    		out = out .. '|}'
    	end
    	-- Add 'new item' link.
    	local _, hyphenCount = currentTitle:gsub( '-', '-' )
    	if hyphenCount < 2 then
	    	local nextSubitem = currentTitle .. '-' .. ( #childItemsResults + 1 )
	    	local formEdit = mw.title.new( 'Special:FormEdit/item/' .. nextSubitem )
			local params = {}
			params[ 'item[parent_item]' ] = currentTitle
	    	out = out .. '<span class="group-user-show">[' .. formEdit:canonicalUrl( params ) .. ' Add new subitem]</span>'
	    end
	end

	-- Set SEO data.
	mw.ext.seo.set( {
		title = title,
		title_mode = 'append',
		description = description,
		image = image,
		image_width = 800,
		keywords = tags,
		citation_date_created = date
	} )

	-- Final output.
	local styles = mw.getCurrentFrame():extensionTag( 'templatestyles', nil, { src = 'Module:Item/styles.css' } )
	return styles .. '<div class="mdl-item">' .. out .. '</div>'
end

p.items = function ( frame )
	local args = {
		where = '',
		limit = 1000,
		orderBy = 'date ASC'
	}
	local fields = '_pageName, title, date, date_precision'
	local results = mw.ext.cargo.query( 'items', fields, args )
	local out = '<ol>'
	for r = 1, #results do
		local item = results[r]
		local dateDisplay = p.formatDate( item.date, item.date_precision )
		out = out .. '<li>' .. dateDisplay .. ': [[' .. item._pageName .. '|' .. item.title .. ']]</li>'
	end
	out = out .. '</ol>'
	return out
end

-- =p.main({args={parent_item='BUFF1'}})
return p