$: << File.dirname(__FILE__)
require 'gosu'
require 'yaml.rb'

#draw rectangle in background
def draw_bg
  draw_quad(0,0,Options::TOP_COLOR, Options::SCREEN_WIDTH, 0, Options::TOP_COLOR, 0, Options::SCREEN_HEIGHT, Options::BOTTOM_COLOR, Options::SCREEN_WIDTH, Options::SCREEN_HEIGHT, Options::BOTTOM_COLOR, Background)
end

class Score < Gosu::Window
  attr_accessor :score_value, :username
   
  def initialize
    super(640, 770, false, 16)
    self.caption = "Back To Black: Score"
   
    @score_value=score_value
    @username = username
    @myscore = Gosu::Font.new(self, 'Arial', 20)
    #check if highscore file was created
    #if not created create a new one
    if(File.exist?('highscores.yml') == false) then
      File.new("highscores.yml", "w")
    end
    @bg_image = Gosu::Image.new(self, "media/scoreScreen.png", false)
    
    @font = Gosu::Font.new(self, 'Arial', 15)   
    @score_value = Gosu::Font.new(self, 'Arial', 20)
    
    @text_highscores = Gosu::Font.new(self, 'Arial', 13)
    @highscores = Array.new

    #get all scores from file
    myfile = File.open("highscores.yml","r+")
    yp = YAML::load_documents( myfile ) { |doc|      
      @temp = Array.new(2)
      @temp[0] = doc['username']
      @temp[1] = doc['score']     
      @highscores.push(@temp)
    }   
    myfile.close
    @highscores_sorted = @highscores.sort_by{|a|Integer(a[1]) * -1}
        
    #fill an other array with the 10 largest values
    @top_scores = Array.new
    @count = 0;
    @highscores_sorted.each do |score|
      if(@count < 10) then
        score[0] = (@count + 1).to_s() + ".  "+score[0]
        @top_scores[@count] = score
        @count +=1
      end
    end
   
    @highscore_y = 360  
     
  end
  
  def button_down(id)
    if id == Gosu::KbReturn             
        game_window = MainMenu.new
        game_window.show
        close
      end
    
    if id == Gosu::KbEscape
      close
    end
  end 
      
  def draw
    @bg_image.draw(0, 0, 0)
       
    #print all highscores
    @top_scores.each do |highscore|
      user = highscore[0]
      score = Integer(highscore[1])
      @text_highscores.draw(user + " " + score.to_s(), 270, @highscore_y, 1, 1, 1, 0xff7c7c7c)      
      @myscore.draw("Score: #{username} #{score_value}", 250,260,1,1,1,0xffd60606)
      @highscore_y += 15
      
      if(@highscore_y > (360 + ((@top_scores.count - 1) * 15)))  then
        @highscore_y = 360
      end     
    end    
  end
end
