extends StaticBody3D

@export var building_id: StringName = &""

@onready var mesh: MeshInstance3D = $Mesh
@onready var collision: CollisionShape3D = $Collision

func _enter_tree() -> void:
  set_multiplayer_authority(1)

func _ready() -> void:
  add_to_group("buildings")
  apply_building(building_id)

func apply_building(id: StringName) -> void:
  building_id = id
  var data: Building = _load_building(id)
  if data == null:
    return
  var box: BoxMesh = mesh.mesh as BoxMesh
  if box:
    box.size = data.size
  var shape: BoxShape3D = collision.shape as BoxShape3D
  if shape:
    shape.size = data.size
  collision.position = Vector3(0.0, data.size.y * 0.5, 0.0)
  mesh.position = Vector3(0.0, data.size.y * 0.5, 0.0)
  var mat: StandardMaterial3D = StandardMaterial3D.new()
  mat.albedo_color = data.color
  mesh.material_override = mat

static func _load_building(id: StringName) -> Building:
  var path := "res://resources/buildings/%s.tres" % str(id)
  if ResourceLoader.exists(path):
    return load(path) as Building
  return null
