export default function defineComponent({ name, template, schema }) {
	name('tdb1:facing_direction')
	schema({
		properties: {
			rotation_from: {
				type: 'string',
				enum: ['player', 'block_face'],
			},
		},
	})

	template(({ rotation_from = 'player' }, { create }) => {
		const rotationLookup = [
			[0.0, 0.0, 0.0],
			[90.0, 0.0, 0.0],
			[0.0, 90.0, -90.0],
		]
		create(
			{
				'tdb1:facing_direction': [0, 1, 2],
			},
			'minecraft:block/description/properties'
		)

		create(
			{
				permutations: rotationLookup.map((rotation, i) => ({
					condition: `query.block_property('tdb1:facing_direction') == ${i}`,
					components: {
						'minecraft:rotation': rotation,
					},
				})),
			},
			'minecraft:block'
		)

		create(
			{
				'minecraft:on_player_placing': {
					event: 'tdb1:set_facing_direction',
				},
			},
			'minecraft:block/components'
		)

		create(
			{
				'tdb1:set_facing_direction': {
					set_block_property: {
						'tdb1:facing_direction': `math.floor(${
							rotation_from === 'player'
								? 'query.cardinal_facing'
								: 'query.block_face'
						} / 2.0)`,
					},
				},
			},
			'minecraft:block/events'
		)
	})
}
