tool

extends Area2D

class_name GameObjectLightbulb

enum Direction { LEFT, RIGHT, UP, DOWN }

export(Direction) var direction = Direction.DOWN setget set_direction
export var lit = true setget set_lit

onready var activationRange = $ActivationRange as ActivationRange
onready var manager = $PowerManager as PowerManager

func _ready():
	if not Engine.editor_hint:
		activationRange.visible = true
	refresh_sprite()

remotesync func set_direction(dir):
	direction = dir
	refresh_sprite()

remotesync func set_lit(val):
	lit = val
	update_light()
	refresh_sprite()

func refresh_sprite():
	var rot = 0
	var lit_offset = 0
	var powered = Engine.editor_hint or (manager != null and manager.powered)
	if not lit or not powered:
		lit_offset = 32
	match direction:
		Direction.DOWN:
			$light.region_rect.position = Vector2(32, lit_offset)
			rot = 0
		Direction.UP:
			$light.region_rect.position = Vector2(0, lit_offset)
			rot = PI
		Direction.LEFT:
			$light.region_rect.position = Vector2(96, lit_offset)
			rot = -PI/2
		Direction.RIGHT:
			$light.region_rect.position = Vector2(64, lit_offset)
			rot = PI/2
	$Light2D.rotation = rot
	$ActivationRange.rotation = rot

func _input_event(_viewport, event, _shape_idx):
	if Engine.editor_hint:
		return
	if event is InputEventMouseButton and event.pressed:
		if activationRange.in_range():
			rpc("set_lit", !lit)

func _power_status_changed(_powered: bool) -> void:
	update_light()
	refresh_sprite()

func update_light():
	$Light2D.enabled = lit and (manager != null and manager.powered)

func serialize():
	return {
		"direction": direction,
		"lit": lit
	}

func deserialize(data):
	set_direction(data["direction"])
	set_lit(data["lit"])
