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

const CRATES = ["tomato-crate", "bun-crate", "steak-crate", "cheese-crate", "lettuce-crate", "mushroom-crate"]
const TOOLS = ["stove", "stove", "stove", "sink", "cutting-board", "sink", "cutting-board", "rolling-board", "oven", "freezer", "deep-fryer", "rolling-board"]
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: Dictionary[Vector2i, Variant] = {} # : Dictionary[Vector2i, 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 tile = null # : String?
			if k > 0.25: tile = "floor"
			if k > 0.4: tile = choose(CRATES) if randf() > 0.7 else "counter"
			if k > 0.6: tile = choose(TOOLS)
			if tile != null:
				tiles[Vector2i(x,y)] = tile
				if tile == "counter" and randf() > 0.5 and w > 0.45:
					item_counters.push_back(Vector2i(x, y))
	var get_tile := func (cs: Vector2i):
		return tiles.get(cs)
	for tile_pos: Vector2i in tiles.keys():
		var x := tile_pos.x
		var y := tile_pos.y
		var tile = get_tile.call(tile_pos)
		if tile != null:
			map.set_tile(Vector2i(x,y), tile,
				[Vector2i(x,y-1),Vector2i(x-1,y),Vector2i(x,y+1),Vector2i(x+1,y)].map(get_tile))

	map.flush()

	for v: Vector2i in item_counters:
		var t: Tile = map.get_tile_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())]
