---------------------------------------------------------------------------------------------------
-- Scene loading stuff
---------------------------------------------------------------------------------------------------

function LoadEntityData(entity, data)
	entity:setName(data.replaceName or data.name)
	entity:setXY(data.x or 0.0,  data.y or 0.0)
	entity:setOrder(data.order or 0)

	if (data.isVisible ~= nil) then
		entity:setVisible(data.isVisible)
	end
	if (data.isRespondable ~= nil) then
		entity:setRespondable(data.isRespondable)
	end
	if (data.isActive ~= nil) then
		entity:setActive(data.isActive)
	end

	entity:setRotationDeg(data.angle or 0)
	entity:setScale(data.scaleX or data.scale or 1.0,  data.scaleY or data.scale or 1.0)
	entity:setOpacity(data.opacity or 1.0)

	entity:setBlend(data.blend  or RenderedObject.EBlendModeDefault)

	local color = data.color or {r = 1.0, g = 1.0, b = 1.0, a = 1.0}
	entity:setColor(color.r, color.g, color.b, color.a)
end

---------------------------------------------------------------------------------------------------

function SetPlaybackOnLoad(entity, data)
	if data.play ~= nil and not data.play then
		entity:stop()
	end
end

---------------------------------------------------------------------------------------------------

function ValidatePath(path)
	if path ~= '' and path ~= nil and not resourceExists(path)
	then
		Application:getPlatform():showMessageBox(path .. ' do not exist')
		return false
	else
		return true
	end
end

---------------------------------------------------------------------------------------------------

function LoadSpriteEntity(data)
	if not ValidatePath(data.texturePath) then data.texturePath = '' end

	local entity = CreateSpriteEntity(data.texturePath or '')

	LoadEntityData(entity, data)

	assert(data.width ~= nil)
	assert(data.height ~= nil)
	entity:setAnimationSize(data.width, data.height)

	if (data.hotSpotX ~= nil  and  data.hotSpotY ~= nil) then  -- for compatibility reasons
		entity:setHotSpot(data.hotSpotX, data.hotSpotY)
	end

	if (data.hotSpot ~= nil) then
		entity:setHotSpot(data.hotSpot.x, data.hotSpot.y)
	end

	entity:setFramesCount(data.framesCount or 1)
	entity:setFPS(data.fps or 0)
	entity:setMode(data.mode or _ANIM_FWD)

	entity:setSmoothed(data.smoothed or false)

	SetPlaybackOnLoad(entity, data)

	return entity
end

---------------------------------------------------------------------------------------------------

function LoadTextEntity(data)
	local entity = CreateTextEntity()

	LoadEntityData(entity, data)

	assert(data.text ~= nil or data.localizationKey ~= nil)
	if (data.localizationKey ~= nil) then
		entity:setText(data.localizationKey)
	else
		entity:setText(data.text)
	end

	if (data.font ~= nil) then
		entity:setFont(data.font)
	end

	if (data.height ~= nil) then
		entity:setHeight(data.height)
	end

	if (data.boundsX ~= nil  and  data.boundsY ~= nil) then
		entity:setBounds(data.boundsX, data.boundsY)
	end

	entity:setHotSpotType(data.hotSpotType or TextEntity.ETextHotSpotTypeCenter)
	entity:setTextAlignment(data.alignment or TextEntity.ETextHorizontalAlignmentCenter)

	return entity
end

---------------------------------------------------------------------------------------------------

function LoadButtonEntity(data)
	if not ValidatePath(data.texturePath) then data.texturePath = '' end

	local entity = CreateButtonEntity(data.texturePath or '')

	LoadEntityData(entity, data)

    if (data.localizationKey ~= nil) then
		entity:setText(data.localizationKey)
	elseif (data.text ~= nil) then
		entity:setText(data.text)
	end

	if (data.activeRectX ~= nil and data.activeRectY ~= nil) then
		entity:setActiveRectSize(data.activeRectX, data.activeRectY)
	end

	return entity
end

---------------------------------------------------------------------------------------------------

function LoadVideoEntity(data)
	if not ValidatePath(data.path) then data.path = '' end

	local entity = CreateVideoEntity(data.path, data.hasAlpha)

	LoadEntityData(entity, data)

	if (data.hotSpot ~= nil) then
		entity:setHotSpot(data.hotSpot.x, data.hotSpot.y)
	end

	entity:setLooped(data.isLooped)

	if data.fps ~= nil then
		entity:setFPS(data.fps)
	end

	if data.soundPath ~= nil then
		entity:setSoundTrack(data.soundPath)
		entity:play()           -- Это делается потому что, setSoundTrack останавливает видео.
	end

	if data.softEdges ~= nil then
		entity:setSoftEdgesSize(data.softEdges)
	end

	SetPlaybackOnLoad(entity, data)

	return entity
end

---------------------------------------------------------------------------------------------------

function LoadCompositionContainer(data)
	local entity = CreateCompositionContainer(data.path)

	LoadEntityData(entity, data)
	entity:attachTo(data.root)

	return entity
end

---------------------------------------------------------------------------------------------------

function LoadCompositionSequence(data)
	--print('Load composition sequence "' .. data.name .. '" for parent "' .. data.parentData.entity:getName() .. '"')
	local entity = data.root:getEntityNamed(data.name)
	LoadEntityData(entity, data)

	if (data.hotSpot ~= nil) then
		entity:setHotSpot(data.hotSpot.x, data.hotSpot.y)
	end

	if data.isCyclic ~= nil then
		entity:setCyclic(data.isCyclic)
	end

	if data.speed ~= nil then
		entity:setSpeed(data.speed)
	end

	SetPlaybackOnLoad(entity, data)

	return entity
end

---------------------------------------------------------------------------------------------------

function RegisterEditableEntityWithParents(data)
	if (data.isRegistered) then
		return
	end

	if (data.parentData ~= nil) then
		RegisterEditableEntityWithParents(data.parentData)
	end

	--print('Registering entity ' .. (data.replaceName or data.name)) -- data.entity:getName())
    RegisterEditableEntity(data.entity, data.editingLocked or false)
	--SetEntityPropertiesRespondable(data.entity, data.isRespondable or false)
	data.isRegistered = true
end

---------------------------------------------------------------------------------------------------

loaders = {}
loaders['SpriteEntity'] = LoadSpriteEntity
loaders['TextEntity'] = LoadTextEntity
loaders['ButtonEntity'] = LoadButtonEntity
loaders['VideoEntity'] = LoadVideoEntity
loaders['CompositionSequence'] = LoadCompositionSequence
loaders['CompositionContainer'] = LoadCompositionContainer

---------------------------------------------------------------------------------------------------

function FindNamedTableItem(table, name)
	for key, data in pairs(table) do
		if data.name == name then
			return data
		end
	end

	return nil
end

---------------------------------------------------------------------------------------------------

if ApplyTextLocalization == nil then
	function ApplyTextLocalization(entity)
		entity:setText(StringManager:getString(entity:getText()))
	end
end

---------------------------------------------------------------------------------------------------

function LoadScene(root, table)
    for key, data in pairs(table) do
        if (type(key) == "string") then  -- for compatibility reasons, remove later
			data.name = key
		end
    end

    -- Добавляем для всех элементов root
    for key, data in pairs(table) do
        data.root = root
    end

-- Establish table parent-child links

	for key, data in pairs(table) do
		if data.parentName then
			data.parentData = FindNamedTableItem(table, data.parentName)
			assert(data.parentData ~= nil)
		end
	end


-- Load CompositionContainer objects first  (since they are creating Sequences as children)

	for key, data in pairs(table) do
	    if data.entityType == 'CompositionContainer' then
	        local loader = loaders[data.entityType]
		    assert(loader ~= nil)
		    data.entity = loader(data)
	    end
	end


-- Load all other types of entities. CompositionSequences will not be really created, but only set up according to stored attributes

	for key, data in pairs(table) do
	    if data.entityType ~= 'CompositionContainer' then
            local loader = loaders[data.entityType]
            assert(loader ~= nil)
            data.entity = loader(data)
		end
	end


-- Attaching child entities to their parents

	for key, data in pairs(table) do
		if (data.entity ~= nil) then
			if data.parentData ~= nil and data.parentData.entity ~= nil then
				data.entity:attachTo(data.parentData.entity)
			else
				data.entity:attachTo(root)
			end
		end
	end


-- Registering on editor Р creating editor tree node objects, attaching them to parent nodes

	if (RegisterEditableEntity ~= nil) then
		for key, data in pairs(table) do
			RegisterEditableEntityWithParents(data)
		end
	end


-- Replacing text keys to localized values. Should be done after RegisterEditableEntity, since keys are stored in that editing nodes

	for key, data in pairs(table) do
		if (data.localizationKey ~= nil) then
			ApplyTextLocalization(data.entity)
		end
	end


-- Expand tree nodes if editor

	if (SetEditorTreeItemIsExpanded ~= nil) then
		for key, data in pairs(table) do
			if (data.entity ~= nil) then
				SetEditorTreeItemIsExpanded(data.entity, data.treeItemIsExpanded or false)
			end
		end
	end
	
-- set Parameter AutoPlay for composition and sprite Entity
    if IS_ERS_EDITOR then
        if SetEntityPropertiesAutoPlay ~= nil then
            for key, data in pairs(table) do
                if data.play ~= nil then
                    SetEntityPropertiesAutoPlay(data.entity, data.play)
                end
            end
        end
    end
end

---------------------------------------------------------------------------------------------------

function CopyObjects(root, table)
	for key, data in pairs(table) do
		-- data.replaceName = FindUniqueNameForCopy(GetWorkspaceRoot(), data.name)
		data.replaceName = FindUniqueName(GetWorkspaceRoot(), data.name)
	end
	
	LoadScene(root, table)
end

---------------------------------------------------------------------------------------------------
