extends KinematicBody2D

# Declare member variables here. Examples:
# var a = 2
# var b = "text"
#onready var label = get_node("Label")
onready var timer = get_node("Timer")
var speed    : = 0.5
var position_tracker = 0.0
var player = null
var obstacle = null
var DisplayValue = 10
var health: int = 2
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
    pass # Replace with function body.

func _physics_process(_delta):
    if player == null:
        translate(Vector2(speed, 0))
        position_tracker += speed
        if position_tracker >= 50 or position_tracker <=0:#enemy move back and forth
            speed *= -1
    if player:
        translate(Vector2(position.direction_to(player.position) * abs(speed))) #enemy follow player

    if obstacle == null:
        $Sprite.texture = load("res://Sprites/Enemies/DarkMatter_barrier.png")

    if obstacle:
        $Sprite.texture = load("res://Sprites/Enemies/DarkMatter.png")
# Called every frame. 'delta' is the elapsed time since the previous frame.
#func _process(delta):
#    pass

func _on_Player_detect_body_entered(body):
    #print("player entered")  # Replace with function body.
    #print(body.name)#"Player"
    if body.name == 'Player': #sometimes map_boundary is detected
    #if body.get_parent().name == 'Player':
        player = body

func _on_Player_detect_body_exited(_body):
    #print("player exit")
    if _body.name == 'Player':
        player = null

func _on_Star_detect_body_entered(body_star):
    #print("obstacle entered")
    #print(body_star.name)#Obstacle
    if 'Star' in body_star.name:
        obstacle = body_star
        timer.set_wait_time(DisplayValue)
        timer.start()
        #print("timer start")

func _on_Star_detect_body_exited(_body):
    #if _body.name == 'Star': 
        #print("obstacle exited")
    #if _body.name == 'Obstacle':
    #obstacle = null
    null

func _on_Timer_timeout():
    #print("time out")
    obstacle = null # Replace with function body.


func _on_Hitbox_area_entered(area: Area2D):
    if obstacle: #when the enemy is vulnerable
        if area.is_in_group('player_weapon_1'):
            health -= 1
        elif area.is_in_group('player_weapon_2'):
            health -= 2

    if health <= 0:
        call_deferred('queue_free')
    return
