extends Node2D

var player = preload("res://scenes/player.tscn")
var instance = null
var playing: bool = false


var enemy_wave: int
var enemy_count: int = 0:
  set(value):
      if value < 0:
          print_debug("Enemy value set to below zero: ", get_stack())
      if value > 27:
          print_debug("Enemy value set to above 27!: ", get_stack())
      enemy_count = value

const COLS: int = 9
const ROWS: int = 3

@onready var start_button = $CanvasLayer/CenterContainer/Start
@onready var game_over = $CanvasLayer/CenterContainer/GameOver

func _ready():
    game_over.hide()
    start_button.show()
    EventBus.player_died.connect(_on_player_died)
    #EventBus.enemy_died.connect(_on_enemy_died)
    EventBus.enemy_hit.connect(_on_enemy_hit)
    EventBus.flash_screen.connect(_on_flash_screen)
    EventBus.win_game.connect(_on_win_game)
    EventBus.secret_win_game.connect(_on_secret_win_game)


#func spawn_enemies(): 
    ## print("Remaining enemies: ", enemy_count)
    ## await get_tree().process_frame
    #enemy_wave += 1
    #print("Enemy Wave: ", enemy_wave)
    #for x in range(COLS):
      #for y in range(ROWS):
            #var e = enemy.instantiate()
            #var pos = Vector2(x * (16 + 8) + 24, 16 * 4 + y * 16)
            #add_child(e)
            #e.start(pos)
            #enemy_count = ROWS * COLS
            #await get_tree().process_frame
            #print_debug("Remaining enemies: ", enemy_count, ", ", get_tree().get_nodes_in_group("enemies").size())
#
#
#
##func _on_enemy_died():
    ##enemy_count -= 1
    ##print_debug(enemy_count)
    ##if enemy_count == 0:
      ##print_debug("Remaining enemies: ", enemy_count, ", ", get_tree().get_nodes_in_group("enemies").size())
      ### win_game()
      ##await get_tree().create_timer(2).timeout
      ##$Wave.spawn_enemies()
    ##if enemy_count == ROWS * COLS / 2:
        ##print_debug("Enemy count is 50%")
        ##update_enemy_aggression(2,10)
        ##EventBus.goose_talk.emit()
    ##if enemy_count == ROWS * COLS / 4:
        ##print_debug("Enemy count is 25%")
        ##update_enemy_aggression(1,1)
#
##func update_enemy_aggression(low,high):
  ##var nodes = get_tree().get_nodes_in_group("enemies")
##
  ##for node in nodes:
   ##if node is Area2D:
     ##node.enemy_move_aggression = randf_range(low,high)
     ##node.enemy_shoot_aggression = randf_range(low,high)
     ##node.tween_speed = min(low,high) - .75

func _on_enemy_hit(value: int):
    Global.score += value
    $CanvasLayer/UI.update_score(Global.score)

func _on_player_died():
    # get_tree().call_group("enemies", "queue_free")
    # $Player.set_process(false)
    # get_tree().call_group("enemies", "set_process", false)
    $SFX/AmbientHiss.stop()
    EventBus.goose_talk.emit(7)
    instance.queue_free()
    game_over.show()
    $LevelAudio.stop()
    await get_tree().create_timer(2).timeout
    game_over.hide()
    $CanvasLayer/Title.show()
    start_button.show()
    playing = false

func new_game():
    $CanvasLayer/Title.hide()
  # Ensure enemies are cleared.
    get_tree().call_group("boss", "queue_free")
    get_tree().call_group("enemies", "queue_free")
    get_tree().call_group("shards", "queue_free")
    get_tree().call_group("enemy_bullets", "queue_free")
    # print("Number of enemies at new_game: ",enemy_count)
    enemy_count = 0
    enemy_wave = 0
    await get_tree().process_frame

  # Reset score.
    Global.score = 0
    $CanvasLayer/UI.update_score(Global.score)

  # Tell the shield to recharge without flashing the player.
    
  # instantiate the Player
    # await get_tree().create_timer(1).timeout
    instance = player.instantiate()  
    add_child(instance)
    $Player.start()
    $SFX/AmbientHiss.play()
    
   # Reset Clouds
    EventBus.cloud_speed.emit(false)
   
    # Do some DapperGoose talk
    await get_tree().create_timer(1.5).timeout
    EventBus.goose_talk.emit(6,4)

  # Tell the enemies to spawn!
    #await get_tree().create_timer(.5).timeout
    $Wave.wave_count = 0
    $Wave.spawn_enemies()
    

  # Tell the game we're playing.
    playing = true
    print("New game started!")
    
  # Play Level Music
    $LevelAudio.play()


func _input(EventInput):
    if EventInput.is_action_pressed("shoot") and playing == false:
        print("Input detected!")
        start_button.hide()
        $Welcome.play()
        new_game()

func _on_start_pressed():
    start_button.hide()
    $Welcome.play()
    new_game()


func _on_secret_win_game():
    playing = false
    game_over.show()
    #await get_tree().create_timer(8).timeout
    game_over.hide()
    $CanvasLayer/Title.show()
    start_button.show()
  

func _on_win_game(value: int):
    
    if value == 1: # Heart Taken
    
      playing = false
      $Player._on_player_victory(1)
      await $Player._on_player_victory(1)
      game_over.show()
      await get_tree().create_timer(5).timeout
      game_over.hide()
      $CanvasLayer/Title.show()
      start_button.show()
      
    if value == 2: #Heart Broken
    
      playing = false
      $Player._on_player_victory(2)
      await $Player._on_player_victory(2)
      game_over.show() 
      await get_tree().create_timer(5).timeout
      game_over.hide()
      $CanvasLayer/Title.show()
      start_button.show()
      
    
func _on_flash_screen(duration: float = .25):
    print("flash!")
    $SFX/Tuner.play()
    $CanvasLayer/ColorRect.visible = true
    await get_tree().create_timer(duration).timeout
    #var tween = create_tween().set_parallel(false)
    #tween.tween_property($CanvasLayer/ColorRect.material, "intensity", 1.0, duration)
    #tween.set_ease(Tween.EASE_IN_OUT).tween_property($CanvasLayer/ColorRect.material, "intensity", 0.0, duration)
    #await tween.finished
    print("flash finished!")
    $CanvasLayer/ColorRect.visible = false
  
