extends Node2D

var Player = preload("res://src/Player.gd")
var Spawner = preload("res://src/Spawner.gd")
var Popup = preload("res://src/Popup.gd")
var Overlay = preload("res://src/Overlay.gd")
var UTIL = preload("res://src/Utility.gd")

var bgImages = []
var bgSpr
var soundDeath = preload("res://sound/death-0.wav")
var soundWin = preload("res://sound/win-0.wav")
var bgMusic = preload("res://music/bgMusic.wav")


var ys
var player
var enemies
var shots
var powerups
var overlay
var minDim
var centerPos
var worldSize
var theEnd = false
var winCount = 42

var gameLayer
var uiLayer

func _init():
  randomize()
#  var a = randi()
  for i in range(7):
    bgImages.append(load("res://images/satanic_bg-" + str(i) + ".png"))
  pass

func _ready():
  minDim = min(get_viewport().size.x, get_viewport().size.y)
  centerPos = Vector2(minDim / 2, minDim / 2)
  worldSize = Vector2(minDim, minDim)
  
  bgSpr = Sprite.new()
#  bgSpr.scale = Vector2(0.01, 0.01)
  bgSpr.set_position(centerPos)
  add_child(bgSpr)
  
  ys = YSort.new()
  ys.set_name("ys")
  add_child(ys)
  uiLayer = CanvasLayer.new()
  uiLayer.set_name("UI")
  add_child(uiLayer)

  overlay = Overlay.new()
  overlay.set_name("overlay")
  uiLayer.add_child(overlay)

  player = Player.new(centerPos)
  player.set_name("player")
  ys.add_child(player)
  var global = get_node("/root/global")
  if global.deaths == null:
    global.deaths = 0
  if global.mutton:
    player.mutton = global.mutton
  overlay.sheepDead.setSheepCount(player.mutton)
  if global.lambs:
    player.lambs = global.lambs
  overlay.sheepLive.setSheepCount(player.lambs)
  
  setBg(player.mutton)
  
  var sheap = Sprite.new()
  sheap.set_name("sheap")
  add_child(sheap)
  
  enemies = YSort.new()
  enemies.set_name("enemies")
  ys.add_child(enemies)
  
  shots = YSort.new()
  shots.set_name("shots")
  ys.add_child(shots)
  
  powerups = YSort.new()
  powerups.set_name("powerups")
  ys.add_child(powerups)
  
  add_child(Spawner.new())

func gameOver():
  if not theEnd:
    theEnd = true
    # sound  
    var asp = AudioStreamPlayer.new()
    self.add_child(asp)
    asp.set_volume_db(-10)
    asp.stream = soundDeath
    asp.play()
    
    add_child(Popup.new('You have died.', 'Press \'R\' to try again. Press \'Space\' to continue.', centerPos, null, null))
    $"/root/World/ys/player".set_process(false)
    
func win():
  if not theEnd:
    theEnd = true
    # sound  
    var asp = AudioStreamPlayer.new()
    self.add_child(asp)
    asp.set_volume_db(0)
    asp.stream = soundWin
    asp.play()
    
    add_child(Popup.new('The Sacrifice is Complete!', \
        'Deaths: ' + str($"/root/global".deaths) + '\t\t\tLiving lambs left: ' + str($"/root/World/ys/player".lambs), centerPos, null, null))

func setBg(mutton):
  bgSpr.set_texture(bgImages[min(6, floor(mutton / 6))])

#func _process(delta):
#  # Called every frame. Delta is time since last frame.
#  # Update game logic here.
#  pass