# Hurry Curry! - a game about cooking
# Copyright (C) 2026 Hurry Curry! Contributors
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, version 3 of the License only.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
class_name Tile
extends Node3D

var base = Node3D.new()
var base_mesh
var item: Item = null
var item_base: Node3D

enum Facing {
	NEG_Y = 0,
	NEG_X = 1,
	Y = 2,
	X = 3,
}

func _init(ctx: TileFactory.TileCC):
	base.name = "Base"
	base.position += Vector3(0.5, 0, 0.5)
	add_child(base)
	self.name = ctx.tile_name.raw_name
	var item_base_ = Node3D.new()
	# this method is supposed to be overriden
	@warning_ignore("static_called_on_instance")

	var item_base_pos = interact_target()
	if item_base_pos == null:
		if ctx.below_tile_instances.is_empty():
			item_base_pos = Vector3.ZERO
		else:
			item_base_pos = ctx.below_tile_instances[-1].item_base.position
	item_base_.position = item_base_pos
	item_base_.name = "ItemBase"
	base.add_child(item_base_)
	item_base = item_base_

	base_mesh = get_base_mesh()
	if base_mesh != null:
		var m: Node3D = base_mesh
		m.position += Vector3(0.5, 0, 0.5)
		add_child(m)
	if not ctx.below_tile_instances.is_empty():
		base.rotation.y = ctx.below_tile_instances[-1].base.rotation.y

func turn_facing(facing: Facing):
	base.rotation.y = facing * 0.5 * PI + PI

# defines where items go when interacting
static func interact_target(): #-> Vector3?
	return null

# actions when interacting, e.g. animations
func interact():
	pass

func progress(position_: float, speed: float, warn: bool, _acting_players: Array[Player]):
	if item != null:
		item.progress(position_, speed, warn)

func finish():
	if item != null:
		item.finish()

func put_item(i: Item):
	if item != null:
		push_error("already holding an item")
	set_item(i)

func pass_to(tile: Tile):
	var i = take_item()
	if tile.item != null:
		push_error("target is already holding an item")
	tile.set_item(i)

func set_item(i: Item):
	if item != null:
		if i != null:
			i.rotation.y = item.rotation.y
			i.rotation_target = item.rotation_target
		item.remove()
	item = i
	if i != null:
		i.owned_by = item_base
		i.position_target = item_base.global_position

func take_item() -> Item:
	var i = item
	item = null
	return i

func get_base_mesh():
	return null

# Called when about to be changed to different tile
# returning false deletes the tile and replaces it normally
# returning true means this function applies the change
func change(_name: String) -> bool:
	return false
