# 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/>.
#
extends Node3D

const CRATES = ["tomato-crate", "bun-crate", "steak-crate", "cheese-crate", "lettuce-crate", "mushroom-crate"]
const TOOLS_WEIGHTED: Dictionary[Array, float] = {
	["stove"]: 3,
	["counter", "sink"]: 2,
	["counter", "cutting-board"]: 2,
	["counter", "rolling-board"]: 2,
	["oven"]: 1,
	["freezer"]: 1,
	["counter", "deep-fryer"]: 1
}
const ITEMS = ["pot", "pan", "foodprocessor", "plate", "basket", "lettuce", "dirty-plate", "cheese"]

@onready var environment: WorldEnvironment = $Environment
@onready var map: Map = $Map

func _ready():
	if !Global.on_vulkan():
		environment.environment.tonemap_exposure = 0.25

	var tiles_dict: Dictionary[Vector2i, Array] = {} # : Dictionary[Vector2i, Array[String]]
	var item_counters := []
	for x in range(-10, 11):
		for y in range(-10, 11):
			var w = exp(-Vector2(x, y).length() * 0.15)
			var k = randf() * w
			var tiles: Array = []
			if k > 0.25: tiles = ["floor"]
			if k > 0.4: tiles = ["floor"] + [choose(CRATES)] if randf() > 0.7 else ["floor", "counter"]
			if k > 0.6: tiles = ["floor"] + choose_weighted(TOOLS_WEIGHTED)
			if not tiles.is_empty():
				tiles_dict[Vector2i(x,y)] = tiles
				if tiles.has("counter") and tiles.size() <= 2 and randf() > 0.5 and w > 0.45:
					item_counters.push_back(Vector2i(x, y))
	map.set_all_tiles(tiles_dict)
	map.flush()

	for v: Vector2i in item_counters:
		var t = map.get_topmost_instance(v)
		var item := ItemFactory.produce(choose(ITEMS), t)
		add_child(item)
		item.position = t.item_base.global_position
		var rot := randf() * 2 * PI
		item.rotation.y = rot
		item.rotation_target = rot
		t.set_item(item)

func choose(a): return a[floor(a.size() * randf())]

func choose_weighted(weighted_options: Dictionary[Array, float]): # -> Array?
	var weight_sum := 0.
	var areas: Dictionary[float, Array] = {}
	for k in weighted_options:
		weight_sum += weighted_options[k]
		areas[weight_sum] = k
	var selection = randf() * weight_sum
	for k in areas:
		if k >= selection:
			return areas[k]
