/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package interactiveproject.spacesimulator;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Ronny
 */
public class Board {

    private int rows;
    private int cols;
    public RealPlayer player;
    private int gems = 0;
    private String level;

    private int width = 0;
    private int height = 0;
    private int offsetLeft = 0;
    private int offsetTop = 0;
    private int cellSize = 0;
    
    
    BufferedImage wall;
    BufferedImage gold;
    BufferedImage enemy;

    public int getRows() {
        return rows;
    }

    public int getCols() {
        return cols;
    }

    String[][] map;

    public String[][] getMap() {
        return map;
    }

    public Board(String filePath) {
        try {
            wall = ImageIO.read(getClass().getResourceAsStream("/interactiveproject/spacesimulator/images/wall.png"));
            gold = ImageIO.read(getClass().getResourceAsStream("/interactiveproject/spacesimulator/images/gem.png"));
            enemy = ImageIO.read(getClass().getResourceAsStream("/interactiveproject/spacesimulator/images/enemy.png"));
            player = new RealPlayer(this);
            level = filePath;
            reset(filePath, true);
        } catch (IOException ex) {
            Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void drawStars(Graphics g, int width, int height, int number) {
        for (int i = 0; i < number; i++) {
            g.setColor(Color.yellow);
            int x = (int) (Math.random() * width);
            int y = (int) (Math.random() * height);
            g.fillOval(x, y, 5, 5);
        }
    }

    public void emptyLevel(int rows, int cols) {
        this.rows = rows;
        this.cols = cols;
        String[][] newMap = new String[rows][cols];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {

                newMap[i][j] = ".";
            }
        }
        map = newMap;
        player.setX(0);
        player.setY(0);
    }

    public void reset(String filePath, boolean isBuildIn) {
        level = filePath;
        player.reset();
        gems = 0;
        try {
            BufferedReader br = null;

            if (isBuildIn) {
                br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/interactiveproject/spacesimulator/level/" + filePath + ".lvl")));
            } else {
                File f = new File(filePath);
                URL url = f.toURI().toURL();
                br = new BufferedReader(new InputStreamReader(url.openStream()));
            }
            String line;
            cols = Integer.valueOf(br.readLine());
            rows = Integer.valueOf(br.readLine());
            //System.out.println(rows+" "+cols);
            map = new String[rows][cols];

            for (int i = 0; i < rows; i++) {
                line = br.readLine();
                for (int j = 0; j < cols; j++) {
                    if (line.substring(j, j + 1).equals("P")) {
                        player.setY(i);
                        player.setX(j);
                        map[i][j] = ".";
                    } else {
                        map[i][j] = line.substring(j, j + 1);
                        if (map[i][j].equals("x")) {
                            gems++;
                        }
                    }
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public boolean isOver() {
        return gems == player.getGems();
    }

    public void draw(Graphics g, int width, int height) {
        g.setColor(Color.BLACK);
        g.fillRect(0, 0, width, height);

        //drawStars(g, width, height, 100);
        g.setColor(Color.yellow);
        this.width = width;
        this.height = height;
        
        cellSize = Math.min(width / cols, height / rows);
        offsetLeft = (width - cols * cellSize) / 2;
        offsetTop = (height - rows * cellSize) / 2;
        
        for (int i = 0; i <= rows; i++) {
            g.drawLine(offsetLeft, offsetTop + i * cellSize, offsetLeft + cols * cellSize, offsetTop + i * cellSize);
        }
        for (int j = 0; j <= cols; j++) {
            g.drawLine(offsetLeft + j * cellSize, offsetTop, offsetLeft + j * cellSize, offsetTop + rows * cellSize);
        }

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (map[i][j].equals("#")) {
                    g.drawImage(wall, offsetLeft + j * cellSize, offsetTop + i * cellSize, cellSize, cellSize, null);
                } else if (map[i][j].equals("x")) {
                    g.drawImage(gold, offsetLeft + j * cellSize, offsetTop + i * cellSize, cellSize, cellSize, null);
                } else if (map[i][j].equals("E")) {
                    g.drawImage(enemy, offsetLeft + j * cellSize, offsetTop + (int) ((i + 0.2) * cellSize), cellSize, (int) (0.7 * cellSize), null);
                }
            }
        }

        if (player != null) {
            player.draw(g, offsetLeft, offsetTop, cellSize);
        }

        if (isOver()) {
            g.setColor(Color.YELLOW);
            int fontSize = height / 7;
            String winString = "Good job! You Win!";
            Font font = new Font("TimesRoman", Font.PLAIN, fontSize);
            g.setFont(font);
            FontMetrics metrics = g.getFontMetrics();

            // Determine the X coordinate for the text
            int x = 0 + (width - metrics.stringWidth(winString)) / 2;
            // Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen)
            int y = 0 + ((height - metrics.getHeight()) / 2) + metrics.getAscent();
            // Set the font

            // Draw the String
            g.drawString(winString, x, y);
        }

    }

    private int getRow(int y)
    {
        if(y < offsetTop || y > height-offsetTop)
        {
            return -1;
        }
        else{
            y -= offsetTop;
            int row = (int) (y/ cellSize);
            return row;
        }
    }
    
    private int getCol(int x)
    {
        if(x < offsetLeft || x > width-offsetLeft)
        {
            return -1;
        }
        else{
            x -= offsetLeft;
            int col = (int) (x/ cellSize);
            return col;
        }
    }
    
    public void placeAsteroid(int x, int y)
    {
        int row = getRow(y);
        int col = getCol(x);
        if(row != -1 && col!=-1)
            map[row][col] = "#";
    }
    
    public void placeEnnemy(int x, int y)
    {
        int row = getRow(y);
        int col = getCol(x);
        if(row != -1 && col!=-1)
            map[row][col] = "E";
    }
    public void placePlayer(int x, int y)
    {
        int row = getRow(y);
        int col = getCol(x);
        if(row != -1 && col!=-1)
        {
            if(map[row][col].equals("#") || map[row][col].equals("E") )
                System.out.println("Cannot place Player on asteroids or ennemies");
            else
            {
                player.setX(col);
                player.setY(row);
            }
        }
    }
    
    public void placeGem(int x, int y)
    {
        int row = getRow(y);
        int col = getCol(x);
        if(row != -1 && col!=-1)
            map[row][col] = "x";
    }
    
    public void remove(int x, int y)
    {
        int row = getRow(y);
        int col = getCol(x);
        if(row != -1 && col!=-1)
            map[row][col] = ".";
        
    }
    
    
    public void saveToFile(String filePath)
    {
        try {
            filePath = filePath+".lvl";
            File f = new File(filePath);
            FileOutputStream fos = new FileOutputStream(filePath);
            OutputStreamWriter out = new OutputStreamWriter(fos, "UTF-8");
            out.write(cols+"\n");
            out.write(rows+"");
            
            for (int i = 0; i < rows; i++) {
                out.write("\n");
                for (int j = 0; j < cols; j++) {
                    if(player.isAt(i, j)){
                        out.write("P");                    
                    }
                    else
                        out.write(map[i][j]+"");
                    
                }
            }
            
            out.close();
            fos.close();
            
        } catch (MalformedURLException ex) {
            Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
 
 
}
