package ru.cdmlex.jtest;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.geom.Rectangle2D;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.ArrayList;

public class GameOverScene extends Scene {
	
	private List<String> lines;
	private int f_sz = 12;
    public GameOverScene(JGame game, int scr, int size) {
        super(game);
		if (scr == 0) {
			lines = new ArrayList<String>();
			lines.add(0, "DANGEON SNAKE");
			lines.add(1, "");
			lines.add(2, "press enter");		
			f_sz = 12;
		}
		else
		if (scr == 1) {
			lines = new ArrayList<String>();
			lines.add(0, "you fall (");
			lines.add(1, "");
			lines.add(2, "press enter");		
			f_sz = 12;			
		}
		else
		if (scr == 2) {
		
			try {
				lines = Files.readAllLines(Paths.get("score.txt"), StandardCharsets.UTF_8);
				for (int i = 0; i < lines.size(); i++) {
					int temp = Integer.parseInt(lines.get(i));
					if (size >= temp) {
						if (size > temp)
							lines.add(i, ""+size);
						break;
					}
				}
				
				try {
					Files.write(Paths.get("score.txt"), lines);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			catch(IOException e) {
				lines = new ArrayList<String>();
			}
			lines.add(0, "You WIN!");
			lines.add(1, "");
			lines.add(2, "you score: " + size);
			lines.add(3, "__________");
			lines.add(4, "Records: ");
			f_sz = 10;
		}		
    }

    @Override
    public void update(long nanosPassed) {
        for (KeyEvent event : game.getInput().getKeyPressedEvents()) {
            if (event.getKeyCode() == KeyEvent.VK_ENTER) {
                game.setScene(new MainScene(game));
            }
        }
    }

    @Override
    public void draw(Graphics2D g) {
        g.setColor(new Color(41, 61, 65));
        g.fillRect(0, 0, game.getScreenSize().width, game.getScreenSize().height);

        g.setFont(new Font("Default", Font.BOLD, f_sz));
        g.setColor(new Color(136, 173, 181));
		
		int y = 1;

		for (String line : lines) {
			String message = (String)line;
			Rectangle2D messageBounds = g.getFontMetrics().getStringBounds(message, g);
			int messageWidth = (int)(messageBounds.getWidth());
			int messageHeight = (int)(messageBounds.getHeight());

			g.drawString(message, 
					160 / 2 - messageWidth / 2, 
					144 / 2 - (messageHeight * lines.size()) / 2 + messageHeight * y
			);
			y++;
		}


    }
}