local p={}

-- функция для оформления таблицы
function p.table(formattedClaims,context, options )
	options.column = (options.column and tonumber(options.column)) or 100
    	
	-- создание текстовой строки со списком оформленых заявлений в табличном виде
	local out = mw.html.create('table')
	if(options.class) then out:attr('class', options.class) end
	if(options.style) then out:attr('style', options.style) end
	if(options.caption) then out:tag('caption'):wikitext(options.caption) end
	local tr1
	local tr2
   	for i, k in ipairs(formattedClaims) do
   		if(i%options.column==1) then
   			tr1=out:tag('tr')
   			if(options['th.class']) then tr1:addClass(options['th.class']) end
   			if(options['th.style']) then tr1:attr('style', options['th.style']) end
			tr2=out:tag('tr')
			if(options['tr.class']) then tr2:addClass(options['tr.class']) end
			if(options['tr.style']) then tr2:attr('style', options['tr.style']) end
   		end
   		tr1:tag('th'):wikitext(k[1])
   		tr2:tag('td'):wikitext(k[2])
    end
    return tostring(out)
end

-- функция для оформления графика (взято из Модуль:Statistical)
function p.graph(formattedClaims,context, options )
	local tempPopulation = nil
	local tempYears = nil
	for _,v in ipairs(formattedClaims) do 
		tempPopulation = (tempPopulation and tempPopulation .. "," or "") .. v[2] 
		tempYears = (tempYears and tempYears .. "," or "") .. v[1]
	end
	local linePlot = require('Модуль:Graph').chartWrapper
	local Diagram = {
		['height'] = options.height or 250,
		['width'] = options.width or 400,
		['y'] = tempPopulation,
		['x'] = tempYears,
		['yAxisMin'] =  options.yAxisMin or 0
	}
	local cframe = mw.getCurrentFrame()
	local json = linePlot(cframe:newChild{ title=cframe.title, args = Diagram}:newChild{})
	return cframe:callParserFunction( '#tag:graph', json )
end

-- функция для оформления ступенчатого графика (взято из Модуль:Statistical)
function p.gist(formattedClaims,context, options )
	local tempHeight = 320
	local tempWidth = 800
	local tempMod = math.fmod (#formattedClaims, 5)
	if #formattedClaims < 40 then 
		tempHeight = 200  + 170 * (#formattedClaims - 1) / 40
		tempWidth = 200 + 600 * (#formattedClaims - 1) / 40
	end
	local tempGroup = ""
	local tempTooltip = ""
	local tempLegend = ""
	for k,v in pairs(formattedClaims) do 
		tempGroup = tempGroup .. v[2] .. ":"
		tempTooltip = tempTooltip .. v[2] .. " (" .. v[1] .. "):"
		if #formattedClaims < 5 or math.fmod (k, 5) == tempMod  then tempLegend = tempLegend .. v[1] end
		tempLegend = tempLegend .. ":"
	end
	tempGroup = string.sub (tempGroup, 1, string.len (tempGroup)-1)
	tempTooltip = string.sub (tempTooltip, 1, string.len (tempTooltip)-1)
	tempLegend = string.sub (tempLegend, 1, string.len (tempLegend)-1)
    local barChart = require('Модуль:Chart')['bar chart'];
	local Diagram = {
		['height'] = options.height or tempHeight,
		['width'] = options.width or tempWidth,
		['group 1'] = tempGroup,
		['tooltip 1'] = tempTooltip,
		['colors'] = options.colors,
		['x legends'] = tempLegend,
		['group names'] = options['group names'],
		['default color'] = options['default color']
		}    	
	local cframe = mw.getCurrentFrame();
	return barChart(cframe:newChild{ title=cframe.title, args = Diagram})
end

-- взять только последнее значение 
function p.last(formattedClaims,context, options )
	return formattedClaims[#formattedClaims][1]
end
function p.last2(formattedClaims,context, options )
	return formattedClaims[#formattedClaims][2]
end
function p.second(formattedClaims,context, options )
	local result = ""
	if(#formattedClaims>1) then result = "<!-- предыдущее значение "..formattedClaims[#formattedClaims-1][2].."-->" end
	return result .. formattedClaims[#formattedClaims][2]
end



function p.formatTable( context, options )
	if ( not context ) then error( 'context not specified' ); end;
	if ( not options ) then error( 'options not specified' ); end;
	if ( not options.entity ) then error( 'options.entity missing' ); end;
	
	if(options.sort) then require('Модуль:Wikidata2.sort').changeselectClaims(context,options) end

    local claims = context.selectClaims( options, options.property );
    if (claims == nil) then
        return '' --TODO error?
    end

    -- Обход всех заявлений утверждения и с накоплением оформленых предпочтительных 
    -- заявлений в таблице
    local formattedClaims = {}

    for _, claim in ipairs(claims) do
        local formattedStatement = context.formatStatement( options, claim )
        local formattedStatement2 = context.formatStatementDefault( context, options, claim )
        -- здесь может вернуться либо оформленный текст заявления
        -- либо строка ошибки nil похоже никогда не возвращается
        if (formattedStatement and formattedStatement2) then
            table.insert(formattedClaims, {formattedStatement,formattedStatement2})
        end
    end

	-- если ничего нет, то ничего и не выдавать
	if(#formattedClaims<=0) then return '' end
    
    options.tablefunction = options.tablefunction  or "table"
    return p[options.tablefunction](formattedClaims,context, options)
end



return p