package WatorWorld;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RectangularShape;

import javax.swing.JPanel;

class WatorPanel extends JPanel{
    
    
   
    public static final int P_WIDTH = 750;
    public static final int P_HEIGHT = 500;
    private static final int ELLIPSE_CUTOFF = 2500;
    
    private Image doubleBufferImage;
    private Rectangle2D.Double background;
    private WatorWorld theWorld;
   
    public WatorPanel(int rows, int cols, double fractionFish, double fractionSharks){
        setBackground(Color.BLUE);
        setPreferredSize(new Dimension(P_WIDTH, P_HEIGHT));
        background = new Rectangle2D.Double(0, 0, P_WIDTH, P_HEIGHT);
        theWorld = new WatorWorld(rows, cols, fractionFish, fractionSharks);
    }
    
    public void reset(int rows, int cols, double fractionFish, double fractionSharks){
        theWorld = new WatorWorld(rows, cols, fractionFish, fractionSharks);
        render();
    }
    
    
    public void update(){
        theWorld.step();
        render();
    }
    
    private void render() {
        Graphics2D dbg;
        
        if(doubleBufferImage == null) {
            doubleBufferImage = createImage((int) background.width, (int) background.height);
        }
        dbg = (Graphics2D) doubleBufferImage.getGraphics();
        
        // draw background
        dbg.setColor(WatorWorld.getOceanColor());
        dbg.fill(background);
        
        double cellWidth = 1.0 * P_WIDTH / theWorld.getNumCols();
        double cellHeight = 1.0 * P_HEIGHT / theWorld.getNumRows();
        
        RectangularShape sh;
        if(theWorld.getNumSpots() < ELLIPSE_CUTOFF)
            sh = new Ellipse2D.Double(0, 0, cellWidth, cellHeight);
        else
            sh = new Rectangle2D.Double(0, 0, cellWidth, cellHeight);
        for(int r = 0; r < theWorld.getNumRows(); r++){
            for(int c = 0; c < theWorld.getNumCols(); c++){
                Color col = theWorld.getColor(r, c);
                if(col != Color.BLUE){
                    dbg.setColor(col);
                    sh.setFrame(c * cellWidth, r * cellHeight, cellWidth, cellHeight);
                    dbg.fill(sh);
                }
            }
        }
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        if(doubleBufferImage == null)
            render();
        g.drawImage(doubleBufferImage, 0, 0, null);
    }

    public WatorWorld getWorld(){
        return theWorld;
    }
}
