extends StaticBody2D

class_name GameObjectDoor

export var object_name := ""
export(NodePath) var interlockTargetPath
var interlockTarget: GameObjectDoor = null

var open_sound := preload("res://Sounds/SFX/effects/door-open.wav")
var close_sound := preload("res://Sounds/SFX/effects/door-close.wav")

export var idle_usage := 2
export var active_usage := 10

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

signal changed(open)

func _ready():
	if is_network_master():
		if interlockTargetPath != null:
			interlockTarget = get_node_or_null(interlockTargetPath)
		if not Engine.editor_hint:
			activationRange.visible = true

master func set_open(open: bool):
	if not manager:
		return
	manager.power_usage = active_usage
	if manager.powered:
		if open:
			if interlockTarget != null:
				interlockTarget.set_open(false)
		rpc("anim_open", open)

remotesync func anim_open(open: bool):
	if open:
		if $Sprite.animation != "open":
			$AudioStreamPlayer2D.stream = open_sound
			$AudioStreamPlayer2D.play()
		$Sprite.play("open")
	else:
		if $Sprite.animation != "close":
			$AudioStreamPlayer2D.stream = close_sound
			$AudioStreamPlayer2D.play()
		$Sprite.play("close")

func _animation_finished():
	if is_network_master():
		if manager:
			manager.power_usage = idle_usage
		if $Sprite.animation == "open":
			# Start timer for auto-close
			$Timer.start()
	if $Sprite.animation == "open":
		# Disable collider
		collision_layer &= ~1
		collision_mask &= ~1
		emit_signal("changed", true)
	else:
		# Enable collider
		collision_mask |= 1
		collision_layer |= 1
		emit_signal("changed", false)

func _input_event(_viewport, event, _shape_idx):
	# Check if we clicked the item
	if event is InputEventMouseButton and event.pressed:
		# Must be in activation range
		if activationRange.in_range():
			rpc("set_open", $Sprite.animation == "close")

master func _close_timer_triggered():
	rpc("set_open", false)

func serialize():
	return {}

func deserialize(_data):
	pass

func inspect():
	return {
		"type": "Airlock",
		"description": "Allows you to move between rooms while keeping rooms air-tight sealed",
		"interaction": "Click when close to manually open/close"
	}

func _open_sensor_triggered():
	rpc("set_open", true)
