local enchantment_sparkle = function(ctx,color)
	return minetest.add_particlespawner {
		amount = 50;
		time = 0.5;
		minpos = vector.subtract(ctx.target.under, 0.5);
		maxpos = vector.add(ctx.target.under, 0.5);
		minvel = {x=0,z=0,y= 0.3}, maxvel = {x=0,z=0,y= 1.5};
		minacc = {x=-0.2,z=-0.2,y=-0.1}, maxacc = {x=0.2,z=0.2,y=-0.2};
		minexptime = 1, maxexptime = 2;
		minsize = 0.5, maxsize = 2;
		texture = sorcery.lib.image('sorcery_spark.png'):multiply(color):render();
		animation = {
			type = 'vertical_frames';
			aspect_w = 16, aspect_h = 16;
			length = 2;
		};
		glow = 14;
	}
end
local anchorwand = function(aff,uses,recipe)
	local affcolor = sorcery.lib.color(sorcery.data.affinities[aff].color)
	return {
		name = aff .. ' anchor';
		desc = 'With an enchanter, anchor ' .. aff .. ' spells into an object to enable it to produce preternatural effects';
		uses = uses;
		affinity = recipe;
		color = affcolor;
		sound = 'xdecor_enchanting'; -- FIXME make own
		cast = function(ctx)
			if (not ctx.target) or ctx.target.type ~= 'node' then return false end
			local node = minetest.get_node(ctx.target.under)
			if node.name ~= 'sorcery:enchanter' then return false end

			local inv = minetest.get_meta(ctx.target.under):get_inventory()
			if inv:is_empty('item') then return false end
			local subj = inv:get_stack('item',1)

			-- now we have everything we need. this part is complex.
			-- first, we need to check the item to see if it is in a
			-- group eligible for enchantment. if so, we then retrieve
			-- the item material and look up the slots offered by this
			-- material. we iterate through the slot definitions to pick 
			-- out a candidate slot, criteria being that the slot
			-- possesses the proper affinity, and that the corresponding
			-- slot on the item enchantment record is empty, then pick
			-- the final slot at random from this table if #candidates>0
			-- (otherwise, we fail unceremoniously).
			--
			-- once we have selected an appropriate slot, we iterate
			-- through the list of known enchantments to check the
			-- affinity of each against `aff`. if the affinity matches
			-- the wand, we then check whether the 'recipe' matches.
			-- if so, we've found the enchantment -- apply it to the
			-- object and update its enchantment data. otherwise, we
			-- move on to the next. if no matching recipe is found,
			-- we give up and bail, returning 'nil' to signify that
			-- a spell was not cast.

			enchantment_sparkle(ctx,affcolor)
		end
	};
end
-- note: this was written before terminology was standardized,
-- and "leytype" corresponds to what is otherwise known as an
-- "affinity"; "affinity" after this comment is widely misused
return {
	flame = {
		name = 'flamebolt';
		color = {255,89,16};
		uses = 64;
		affinity = {'acacia','blazing'};
		leytype = 'praxic';
		desc = 'Conjure a gout of fire to scorch your foes with a flick of this wand';
		cast = function(ctx)
			local speed = 30 -- TODO maybe amethyst tip increases speed?
			local heading = ctx.heading
			heading.pos.y = heading.pos.y + 1.5 -- TODO maths
			local bolt = minetest.add_entity(heading.pos,'sorcery:spell_projectile_flamebolt')
			bolt:set_rotation(heading.yaw)
			local vel = {
				x = heading.yaw.x * speed;
				y = heading.yaw.y * speed;
				z = heading.yaw.z * speed;
			};
			bolt:set_velocity(vel)
		end;
	};
	seal = {
		name = 'sealing';
		color = {255,238,16};
		uses = 32;
		desc = 'Bind an object to your spirit such that it will be rendered impregnable to others, or break a sealing created with this same wand';
		leytype = 'imperic';
		affinity = {'pine','dark'};
		cast = function(ctx)
			if ctx.target == nil or ctx.target.type ~= 'node' then return false end
			local meta = minetest.get_meta(ctx.target.under)
			-- first we need to check if the wand has an identifying 'key' yet,
			-- and set one if not.
			local wandmode = ctx.base.gem == 'amethyst'
			local keycode
			if ctx.meta:contains('sorcery_wand_key') then
				keycode = ctx.meta:get_string('sorcery_wand_key')
			else
				keycode = sorcery.lib.str.rand(32)
				ctx.meta:set_string('sorcery_wand_key', keycode)
			end
			if meta:contains('owner') then
				-- owner is already set -- can we break the enchantment?
				if meta:get_string('sorcery_wand_key') == keycode then
					meta:set_string('owner','')
					meta:set_string('sorcery_wand_key','')
					meta:set_string('sorcery_seal_mode','')
					enchantment_sparkle(ctx,sorcery.lib.color(101,255,142))
				else return false end
			else
				meta:set_string('sorcery_wand_key',keycode)
				meta:set_string('owner',ctx.caster:get_player_name())
				if wandmode then
					meta:set_string('sorcery_seal_mode','wand')
				end
				enchantment_sparkle(ctx,sorcery.lib.color(255,201,27))
			end
		end;
	};
	leyspark = {
		name = 'Leyspark';
		leytype = 'cognic';
		affinity = {'apple','silent'};
		uses = 64;
		desc = 'Reveal the strength and affinities of the local leyline';
		cast = function(ctx)
			local color = ctx.base.gem == 'sapphire';
			local ley = sorcery.ley.estimate(ctx.caster:get_pos())
			local emit = function(color,strength)
				minetest.add_particlespawner {
					amount = 70 * strength;
					time = 2 * strength;
					attached = ctx.caster;
					texture = sorcery.lib.image('sorcery_spark.png'):
						multiply(color):render();
					minpos = { x =  0.5, z =  0.0, y =  1.5}; 
					maxpos = { x =  0.5, z =  0.0, y =  1.5}; 
					minvel = { x = -0.5, z = -0.5, y = -0.5};
					maxvel = { x =  0.5, z =  0.5, y =  0.5};
					minacc = { x =  0.0, z =  0.0, y =  0.5};
					minacc = { x =  0.0, z =  0.0, y =  0.5};
					minsize = 0.4, maxsize = 0.8;
					minexptime = 1, maxexptime = 1;
					glow = 14;
					animation = {
						type = 'vertical_frames';
						aspect_w = 16;
						aspect_h = 16;
						length = 1.1;
					};
				}
			end

			local strength = ley.force
			if color then
				strength = strength / #ley.aff
				for _,a in pairs(ley.aff) do
					emit(sorcery.lib.color(sorcery.data.affinities[a].color), strength)
				end
			else
				emit(sorcery.lib.color(250,255,185), strength)
			end

		end;
	};
	dowse = {
		name = 'dowsing';
		leytype = 'cognic';
		affinity = {'acacia','dark','silent'};
		uses = 128;
		desc = 'Send up sparks of radia to indicate nearness or absence of attuned blocks';
	};
	verdant = {
		name = 'verdant';
		color = {16,29,255};
		uses = 48;
		leytype = 'imperic';
		desc = 'Pour life-energy into the soil, causing flowers and trees to spring up at your command';
		affinity = {'jungle','verdant'};
	};
	praxic        = anchorwand('praxic',       16, {'pine','shimmering','blazing'});
	counterpraxic = anchorwand('counterpraxic',23, {'pine','shimmering','silent'});
	entropic      = anchorwand('entropic',      8, {'jungle','dark'});
	syncretic     = anchorwand('syncretic',    12, {'aspen','verdant','shimmering','blazing'});
	cognic        = anchorwand('cognic',       36, {'acacia','verdant','dark'});
	shape = {
		name = 'shaping';
		uses = 24;
		affinity = {'apple','blazing'};
		desc = 'With an enchanter, physically alter the mundane qualities of an object';
	};
	attune = {
		name = 'attunement';
		uses = 38;
		leytype = 'syncretic';
		affinity = {'pine','verdant','dark'};
		desc = 'Establish a connection between mystic mechanisms, like connecting two sides of a portal or impressing targets onto a dowsing wand in an enchanter';
	};
	meld = {
		name = 'melding';
		uses = 48;
		leytype = 'syncretic';
		affinity = {'apple','verdant'};
		desc = 'Meld the properties of three balanced items on an enchanter to create a new one with special properties, but destroying the old ones and losing two thirds of the mass in the process. The precise outcome is not always predictable.';
	};
	divide = {
		name = 'division';
		uses = 19;
		leytype = 'syncretic';
		affinity = {'apple','shimmering'};
		desc = 'Shatter an item on an enchanter, dividing its essence equally into three parts and precipitating it into new items embodying various properties of the destroyed item. The outcome is not always predictable.';
	};
	obliterate = {
		name = 'obliteration';
		uses = 129;
		affinity = {'aspen','dark'};
		leytype = 'occlutic';
		desc = 'Totally and irreversibly obliterate all items on an enchanter.';
	};
	sacrifice = {
		name = 'sacrifice';
		uses = 58;
		affinity = {'aspen','blazing'};
		leytype = 'syncretic';
		desc = 'Transform the matter of one to three items on an enchanter into energy and empower the item on the center of the enchanter with it. Useful to recharge wands in areas with weak leylines.';
	};
	transfer = {
		name = 'transfer';
		uses = 65;
		leytype = 'syncretic';
		affinity = {'aspen','shimmering','silent'};
		desc = 'Transfer ley-current from items on an enchanter into the item in the center, but at a 50% loss if they are of mismatched affinities. One third of maximum current is transferred, and when used on items with little power may destroy them or their enchantments';
	};
	disjoin = {
		name = 'disjunction';
		uses = 32;
		leytype = 'occlutic';
		affinity = {'jungle','silent'};
		desc = 'With an enchanter, disjoin the anchor holding a spell into an object so a new spell can instead be bound in';
	};
}
