-- IndustrialTest
-- Copyright (C) 2024 mrkubax10

-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.

-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.

-- You should have received a copy of the GNU General Public License
-- along with this program.  If not, see <http://www.gnu.org/licenses/>.

local function addNodeToNetwork(pos,networkMasterPos)
	local meta=minetest.get_meta(pos)
	local networks={}
	if meta:contains("industrialtest.networks") then
		networks=minetest.deserialize(meta:get_string("industrialtest.networks"))
	end
	for _,network in ipairs(networks) do
		if network.x==networkMasterPos.x and network.y==networkMasterPos.y and network.z==networkMasterPos.z then
			return
		end
	end
	table.insert(networks,networkMasterPos)
	meta:set_string("industrialtest.networks",minetest.serialize(networks))
end

local function clampFlow(pos,flow)
	local def=minetest.registered_nodes[minetest.get_node(pos).name]
	local newFlow
	if def.groups and def.groups._industrialtest_cable then
		newFlow=def._industrialtest_cableFlow
	else
		local meta=minetest.get_meta(pos)
		newFlow=meta:get_int("industrialtest.powerFlow")
	end
	return math.min(flow,newFlow)
end

-- \brief Finds path from pos to dest in network. Function finished if either dest is found or every node was visited
-- \param pos Vector
-- \param dest Vector
-- \returns table or nil
function industrialtest.api.findPathInNetwork(pos,dest)
	local connections=industrialtest.api.getConnections(pos,"i")
	if #connections==0 then
		return nil
	end

	local workers={}
	local serializedSourcePos=pos.x..","..pos.y..","..pos.z
	local visitedNodes={[serializedSourcePos]=true}
	for _,conn in ipairs(connections) do
		local sideVector=vector.subtract(conn,pos)
		table.insert(workers,{
			position=conn,
			direction=sideVector,
			path={[1]=conn}
		})
	end

	while #workers>0 do
		for i=1,#workers do
			local worker=workers[i]
			local serializedPos=worker.position.x..","..worker.position.y..","..worker.position.z
			if visitedNodes[serializedPos] then
				table.remove(workers,i)
				break
			end
			visitedNodes[serializedPos]=true

			if worker.position.x==dest.x and worker.position.y==dest.y and worker.position.z==dest.z then
				return worker.path
			end

			local def=minetest.registered_nodes[minetest.get_node(worker.position).name]
			if def and def.groups and def.groups._industrialtest_cable then
				connections=industrialtest.api.getConnections(worker.position,"i")
				for j=1,#connections do
					local direction=vector.subtract(connections[j],worker.position)
					local oppositeDirection=vector.multiply(worker.direction,vector.new(-1,-1,-1))
					if direction.x~=oppositeDirection.x or direction.y~=oppositeDirection.y or direction.z~=oppositeDirection.z then
						if worker.direction.x~=direction.x or worker.direction.y~=direction.y or worker.direction.z~=direction.z then
							table.insert(worker.path,worker.position)
						end
						for c=1,#connections do
							local nextDirection=vector.subtract(connections[c],worker.position)
							if c~=j and (nextDirection.x~=oppositeDirection.x or nextDirection.y~=oppositeDirection.y or nextDirection.z~=oppositeDirection.z) then
								local newWorker={
									position=connections[c],
									direction=nextDirection,
									path=table.copy(worker.path)
								}
								table.insert(newWorker.path,worker.position)
								table.insert(workers,newWorker)
							end
						end
						worker.direction=direction
						worker.position=connections[j]
						break
					end
				end

				if #connections>2 then
					break
				end
			else
				table.remove(workers,i)
				break
			end
		end
	end

	return nil
end

-- \brief Goes through path vertices specified by path running callback on each node.
--        Function finishes if either callback returns false or entire path is went over.
-- \param path table
-- \param callback function
-- \returns nil
function industrialtest.api.walkPath(path,callback)
	local pos=path[1]
	for i=2,#path do
		local pathNode=path[i]
		local direction=vector.normalize(vector.subtract(pathNode,pos))
		while pos.x~=pathNode.x or pos.y~=pathNode.y or pos.z~=pathNode.z do
			if not callback(pos) then
				return
			end
			pos=vector.add(pos,direction)
		end
	end
end

-- \brief Transfers power from source node to it's network, if sides is set then power will be only transfered to network connected to that sides
-- \param pos Vector with position of source node
-- \param (optional) sides table with Vectors
-- \param (optional) flowOverride number
-- \returns two values: true if any neighbouring node has room for more power, false otherwise
--                      true if any power was transferred, false otherwise
function industrialtest.api.powerFlow(pos,sides,flowOverride)
	local meta=minetest.get_meta(pos)
	-- if machine doesn't have network map then it's not capable of transferring power
	local network=industrialtest.api.getNetwork(meta)
	if not network or #network==0 then
		return false,false
	end
	local endpointCount=0
	for _,endpoint in ipairs(network) do
		local endpointMeta=minetest.get_meta(endpoint.position)
		if not industrialtest.api.isFullyCharged(endpointMeta) and (not sides or sides[endpoint.sourceSide]) then
			endpointCount=endpointCount+1
		end
	end
	if endpointCount==0 then
		return false,false
	end

	local ioConfig=industrialtest.api.getIoConfig(meta)
	local transferred=false
	local roomAvailable=false
	for _,endpoint in ipairs(network) do
		if not sides or sides[endpoint.sourceSide] then
			local flow
			if flowOverride then
				flow=flowOverride
			elseif type(ioConfig)=="string" then
				flow=math.min(meta:get_int("industrialtest.powerAmount"),meta:get_int("industrialtest.powerFlow"))
			else
				flow=math.min(meta:get_int("industrialtest.powerAmount"),ioConfig[endpoint.sourceSide].flow)
			end
			local powerDistribution=math.floor(flow/endpointCount)
			local endpointMeta=minetest.get_meta(endpoint.position)
			if powerDistribution<=endpoint.flow then
				local transferredPower=industrialtest.api.transferPower(meta,endpointMeta,powerDistribution)
				if transferredPower>0 then
					transferred=true
				end
				local def=minetest.registered_nodes[minetest.get_node(endpoint.position).name]
				if def and def._industrialtest_self then
					def._industrialtest_self:updateFormspec(endpoint.position)
					if def._industrialtest_self.onPowerFlow and transferredPower>0 then
						def._industrialtest_self:onPowerFlow(endpoint.position,industrialtest.api.getOppositeSide(endpoint.side),transferredPower)
					end
					def._industrialtest_self:triggerIfNeeded(endpoint.position)
				else
					-- Support for bare definitions that don't use industrialtest pseudo-OOP
					minetest.get_node_timer(endpoint.position):start(industrialtest.config.updateDelay)
				end
				if not industrialtest.api.isFullyCharged(endpointMeta) then
					roomAvailable=true
				end
			else
				local path=industrialtest.api.findPathInNetwork(pos,endpoint.position)
				if path and #path>0 then
					table.insert(path,endpoint.position)
					local removed=false
					industrialtest.api.walkPath(path,function(pathPos)
						local def=minetest.registered_nodes[minetest.get_node(pathPos).name]
						if not def or not def.groups or not def.groups._industrialtest_cable then
							return false
						end
						if powerDistribution>def._industrialtest_cableFlow then
							removed=true
							minetest.swap_node(pathPos,{
								name="air"
							})
							minetest.remove_node(pathPos)
							minetest.check_for_falling(pathPos)
							minetest.sound_play("default_cool_lava",{
								pos=pathPos,
								max_hear_distance=5,
								gain=0.7
							})
						end
						return true
					end)
					if not removed and powerDistribution>endpoint.originalFlow then
						minetest.remove_node(endpoint.position)
						industrialtest.internal.explode(endpoint.position,2)
					end
					industrialtest.api.createNetworkMapForNode(pos)
				end
			end
		end
	end
	return roomAvailable,transferred
end

-- \brief Creates network map starting from node at pos, optionally omitting node at omit
-- \param pos vector
-- \param (optional) addCables bool
-- \param (optional) omit Vector
-- \returns table with network map
function industrialtest.api.createNetworkMap(pos,addCables,omit)
	local map={}
	local connections=industrialtest.api.getConnections(pos,"i")
	if #connections==0 then
		return map
	end

	local sourceMeta=minetest.get_meta(pos)
	local workers={}
	local sides={
		["-1,0,0"]=1,
		["1,0,0"]=2,
		["0,-1,0"]=3,
		["0,1,0"]=4,
		["0,0,-1"]=5,
		["0,0,1"]=6
	}
	local serializedSourcePos=pos.x..","..pos.y..","..pos.z
	local visitedNodes={[serializedSourcePos]=true}
	for _,conn in ipairs(connections) do
		if not omit or conn.x~=omit.x or conn.y~=omit.y or conn.z~=omit.z then
			local sideVector=vector.subtract(conn,pos)
			local serializedSideVector=sideVector.x..","..sideVector.y..","..sideVector.z
			local sourceSide=industrialtest.api.normalizeSide(pos,sides[serializedSideVector])
			table.insert(workers,{
				position=conn,
				direction=sideVector,
				distance=1,
				flow=industrialtest.api.getPowerFlowForSide(sourceMeta,sourceSide),
				sourceSide=sourceSide
			})
		end
	end

	while #workers>0 do
		for i=1,#workers do
			local worker=workers[i]
			local serializedPos=worker.position.x..","..worker.position.y..","..worker.position.z
			if visitedNodes[serializedPos] or (omit and omit==worker.position) then
				table.remove(workers,i)
				break
			end
			visitedNodes[serializedPos]=true
			addNodeToNetwork(worker.position,pos)

			local def=minetest.registered_nodes[minetest.get_node(worker.position).name]
			if def and def.groups and def.groups._industrialtest_cable then
				if addCables then
					table.insert(map,{
						position=worker.position,
						distance=worker.distance,
						flow=clampFlow(worker.position,worker.flow),
						side=0,
						sourceSide=worker.sourceSide
					})
				end
				connections=industrialtest.api.getConnections(worker.position,"i")
				if #connections==0 then
					table.remove(workers,i)
					break
				end
				worker.flow=clampFlow(worker.position,worker.flow)
				worker.distance=worker.distance+1
				for i=2,#connections do
					table.insert(workers,{
						position=connections[i],
						direction=vector.subtract(connections[i],worker.position),
						distance=worker.distance,
						flow=worker.flow,
						sourceSide=worker.sourceSide
					})
				end
				worker.direction=vector.subtract(connections[1],worker.position)
				worker.position=connections[1]
				if #connections>=2 then
					break
				end
			else
				local meta=minetest.get_meta(worker.position)
				local incomingSide=industrialtest.api.normalizeSide(worker.position,sides[worker.direction.x..","..worker.direction.y..","..worker.direction.z])
				local connectionSide=industrialtest.api.getOppositeSide(incomingSide)
				local flow=industrialtest.api.getPowerFlowForSide(meta,connectionSide)
				table.insert(map,{
					position=worker.position,
					distance=worker.distance,
					flow=math.min(worker.flow,flow),
					originalFlow=flow,
					side=connectionSide,
					sourceSide=worker.sourceSide
				})
				table.remove(workers,i)
				break
			end
		end
	end

	return map
end

function industrialtest.api.removeNodeFromNetwork(pos,nodePos)
	local meta=minetest.get_meta(pos)
	if not meta:contains("industrialtest.network") then
		return
	end
	local network=minetest.deserialize(meta:get_string("industrialtest.network"))
	local removed=false
	for key,node in ipairs(network) do
		if node.position.x==nodePos.x and node.position.y==nodePos.y and node.position.z==nodePos.z then
			table.remove(network,key)
			removed=true
			break
		end
	end
	if removed then
		meta:set_string("industrialtest.network",minetest.serialize(network))
	end
end

-- \brief Creates network map and writes it to node metadata at pos, optionally omitting node at omit
-- \param pos Vector
-- \param (optional) omit Vector
-- \returns nil
function industrialtest.api.createNetworkMapForNode(pos,omit)
	local meta=minetest.get_meta(pos)
	local network=industrialtest.api.createNetworkMap(pos,false,omit)
	meta:set_string("industrialtest.network",minetest.serialize(network))
end

-- \brief Returns true if meta contains network map, false otherwise
-- \param meta MetaDataRef
-- \returns bool
function industrialtest.api.isNetworkMaster(meta)
	return meta:contains("industrialtest.network")
end

-- \brief Returns network table if node containing meta belongs to any networks, false otherwise
-- \param meta MetaDataRef
-- \returns bool or table
function industrialtest.api.isAttachedToNetwork(meta)
	if not meta:contains("industrialtest.networks") then
		return false
	end
	local networks=minetest.deserialize(meta:get_string("industrialtest.networks"))
	if #networks==0 then
		return false
	end
	return networks
end

-- \brief Returns network master network from it's meta, if meta doesn't contain network map then function returns false
-- \param meta MetaDataRef
-- \returns table or bool
function industrialtest.api.getNetwork(meta)
	if not meta:contains("industrialtest.network") then
		return false
	end
	return minetest.deserialize(meta:get_string("industrialtest.network"))
end

-- \brief Returns amount of power that will flow from specified network master
-- \param pos Vector
-- \returns number
function industrialtest.api.getFlowingCurrent(pos)
	local meta=minetest.get_meta(pos)
	if not industrialtest.api.hasPowerStorage(meta) or meta:get_int("industrialtest.powerAmount")==0 then
		return 0
	end
	local network=industrialtest.api.getNetwork(meta)
	if not network then
		return 0
	end

	local amount=meta:get_int("industrialtest.powerAmount")
	if amount==0 then
		return 0
	end
	local demand=0
	for _,endpoint in ipairs(network) do
		local endpointMeta=minetest.get_meta(endpoint.position)
		if industrialtest.api.hasPowerStorage(endpointMeta) then
			demand=demand+math.min(endpointMeta:get_int("industrialtest.powerCapacity")-endpointMeta:get_int("industrialtest.powerAmount"),endpoint.flow)
		end
	end

	return math.min(amount,demand)
end

-- \brief Returns connections of node with power storage. If direction is "i" only input connections will be returned, if direction is "o" only output connections
--        will be returned, if it's not provided all connections will be returned.
-- \param pos Vector
-- \param (optional) direction string
-- \returns table
function industrialtest.api.getConnections(pos,direction)
	local result={}
	local neighbourPositions={
		vector.offset(pos,-1,0,0),
		vector.offset(pos,1,0,0),
		vector.offset(pos,0,-1,0),
		vector.offset(pos,0,1,0),
		vector.offset(pos,0,0,-1),
		vector.offset(pos,0,0,1)
	}
	local sourceMeta=minetest.get_meta(pos)
	local sourceDef=minetest.registered_nodes[minetest.get_node(pos).name]
	local directionOutput=(not direction or direction=="o")
	local directionInput=(not direction or direction=="i")
	for key,conn in ipairs(neighbourPositions) do
		local meta=minetest.get_meta(conn)
		local def=minetest.registered_nodes[minetest.get_node(conn).name]
		local normalizedKey=industrialtest.api.normalizeSide(pos,key)
		local powerOutput=(sourceDef.groups._industrialtest_cable or industrialtest.api.isPowerOutput(sourceMeta,normalizedKey))
		local powerInput=(sourceDef.groups._industrialtest_cable or industrialtest.api.isPowerInput(sourceMeta,normalizedKey))
		if def.groups._industrialtest_cable or industrialtest.api.hasPowerStorage(meta) then
			local side=industrialtest.api.normalizeSide(conn,industrialtest.api.getOppositeSide(key))
			if (powerOutput and directionInput and (def.groups._industrialtest_cable or industrialtest.api.isPowerInput(meta,side))) or ((def.groups._industrialtest_cable or industrialtest.api.isPowerOutput(meta,side)) and powerInput and directionOutput) then
				table.insert(result,conn)
			end
		end
	end
	return result
end
