# Hurry Curry! - a game about cooking
# Copyright (C) 2025 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 WallTile
extends Floor

static func create_material(color: Color):
	var mat = StandardMaterial3D.new()
	mat.albedo_color = color
	return mat

static var MATERIALS := {
	"red": create_material(Color(0.777, 0.244, 0.187, 1.0)),
	"green": create_material(Color(0.18, 0.745, 0.596, 1.0)),
	"blue": create_material(Color(0.466, 0.519, 0.939, 1.0)),
}

const WALLS: Array = [
	"wall",
	"wall-window",
	"counter-window",
	"door",
	"fence"
]

var walls: Array = WALLS
var env: Array = []

enum WallKind {
	STRAIGHT,
	OUTER_CORNER,
	T,
	CROSS,
}

var kind: WallKind = WallKind.STRAIGHT
var facing: int = 0

func _init(ctx: TileFactory.TileCC):
	super(ctx)

	var max_series: int = 0
	var max_idx: int = 0
	for start in range(4):
		var series = 0
		for i in range(4):
			var i_name = ctx.neighbors[(start + i) % 4]
			if is_wall(i_name):
				series += 1
			else:
				break
		if series > max_series:
			max_series = series
			max_idx = start

	if max_series == 1:
		facing = max_idx
		kind = WallKind.STRAIGHT
		if not env.is_empty() and env.has(ctx.neighbors[(facing + 1) % 4]) or ctx.neighbors[(facing + 1) % 4] == null:
			facing = (facing + 2) % 4
	elif max_series == 2:
		facing = max_idx
		kind = WallKind.OUTER_CORNER
	elif max_series == 3:
		facing = max_idx
		kind = WallKind.T
	elif max_series == 4:
		facing = max_idx
		kind = WallKind.CROSS
	turn_facing(facing)

func add_dyed_mesh(ctx: TileFactory.TileCC, node: Node3D, node_name = "Mesh", surface = 0):
	var meshi: MeshInstance3D = node.get_node(node_name)
	meshi.set_surface_override_material(surface, MATERIALS.get(ctx.tile_name.variant, MATERIALS["green"]))
	base.add_child(node)

func is_wall(tile_name_t) -> bool:
	return walls.has(tile_name_t)
