-- LUALOCALS < ---------------------------------------------------------
local core, nc, vector
    = core, nc, vector
-- LUALOCALS > ---------------------------------------------------------

local modname = core.get_current_modname()

local function prism_check(_, node, recv)
	local face = nc.facedirs[node.param2]

	if recv(face.t) or recv(face.b) then
		return modname .. ":prism_gated"
	end
	if recv(face.f) or recv(face.r) then
		return modname .. ":prism_on"
	end
	return modname .. ":prism"
end

local txr = modname .. "_glass_frost.png"
local pact = modname .. "_port_active.png"
local pout = modname .. "_port_output.png"
local pinp = modname .. "_port_wide.png"
local pina = modname .. "_port_wide_act.png"
local shin = modname .. "_shine_end.png"
local dark = modname .. "_port_input.png"

local basedef = {
	description = "Prism",
	drawtype = "mesh",
	mesh = "nc_optics_prism.obj",
	selection_box = nc.fixedbox(
		{-7/16, -7/16, -7/16, 7/16, 7/16, 7/16}
	),
	tiles = {
		txr,
		txr .. "^" .. pout,
		txr .. "^" .. pinp
	},
	backface_culling = true,
	groups = {
		silica = 1,
		optic_check = 1,
		cracky = 3,
		silica_prism = 1,
		scaling_time = 125,
		optic_gluable = 1,
		nc_api_rotate_under = 1,
	},
	silktouch = false,
	drop = modname .. ":prism",
	on_construct = nc.optic_check,
	on_destruct = nc.optic_check,
	on_nc_rotate = nc.optic_immediate,
	after_place_node = nc.optic_immediate,
	optic_check = prism_check,
	paramtype = "light",
	paramtype2 = "facedir",
	nc_param2_equivalent = function(a, b)
		return vector.equals(a.f, b.r)
		and vector.equals(a.r, b.f)
	end,
	on_rightclick = nc.rotation_on_rightclick,
	sounds = nc.sounds("nc_optics_glassy"),
	nc_optic_family = "prism",
	mapcolor = {r = 139, g = 187, b = 212},
}

local function reg(suff, def)
	core.register_node(modname .. ":prism" .. suff,
		nc.underride(def, basedef))
end
reg("", {})
reg("_on", {
		description = "Active Prism",
		tiles = {
			txr .. "^(" .. pact .. "^[opacity:96)",
			txr .. "^" .. pact .. "^" .. pout,
			txr .. "^" .. pinp .. "^" .. pina
		},
		light_source = 1,
		groups = {optic_source = 1},
		optic_source = function(_, node)
			local fd = nc.facedirs[node.param2]
			return {fd.k, fd.l}
		end
	})
reg("_gated", {
		description = "Gated Prism",
		tiles = {
			txr .. "^" .. shin .. "^" .. pout,
			txr .. "^" .. shin .. "^" .. dark,
			txr .. "^" .. shin .. "^" .. dark
		},
		light_source = 1
	})
