extends Node2D

signal openedSignal

var pattern = [1,8,-1,8,1]
var patternIndex = 0

var opened = false
var fullyMoved = false

var moveSpeed = -25

var amountMoved = 0
var amountToMove = 250

var timeWaited = 0

func _ready():
	GameVariables.globalMessage.connect(global_message_recieved)

func _process(delta):
	if patternIndex < pattern.size() and pattern[patternIndex] == -1:
		timeWaited += delta
		if timeWaited >= 3:
			timeWaited = 0
			patternIndex += 1
			print("ready")
	
	if opened and !fullyMoved:
		var amountToMoved = moveSpeed*delta
		position.x += amountToMoved
		amountMoved += abs(amountToMoved)
		
		if amountMoved >= amountToMove:
			fullyMoved = true

func global_message_recieved(message:String):
	if message.substr(0,4) == "doot":
		var dootNumber = message.substr(4,5)
		
		if pattern[patternIndex] == -1:
			patternIndex = 0
			timeWaited = 0
			if pattern[patternIndex] == int(dootNumber):
				patternIndex += 1
		elif pattern[patternIndex] == int(dootNumber):
			patternIndex += 1
			if patternIndex >= pattern.size():
				open()
				patternIndex = 0
				timeWaited = 0
		else:
			patternIndex = 0
			timeWaited = 0
			if pattern[patternIndex] == int(dootNumber):
				patternIndex += 1

func open():
	opened = true
	openedSignal.emit()
