import processing.core.PApplet;

public class FaceGrid extends PApplet
{
    public static final int TOP_OFFSET = 20;
    public static final int LEFT_OFFSET = 15;
    public static final int BOX_WIDTH = 75;
    public static final int BOX_HEIGHT = 75;
    public static final int ROWS = 5;
    public static final int COLUMNS = 8;
    
    private Face[][] faces;
    
    public static void main(String[] args)
    {
        PApplet.main("FaceGrid");
    }
    
    public void settings()
    {
        final int SCREEN_WIDTH = (LEFT_OFFSET * 2) + (COLUMNS * BOX_WIDTH);
        final int SCREEN_HEIGHT = (TOP_OFFSET * 2) + (ROWS * BOX_HEIGHT);
        size(SCREEN_WIDTH, SCREEN_HEIGHT);
    }
    
    public void setup()
    {
        faces = new Face[ROWS][COLUMNS];
        noLoop();
        redraw();
    }
    
    public void draw()
    {
        background(0);
        
        drawGrid();
        
        for(int row = 0; row < faces.length; row++)
        {
            for(int col = 0; col < faces[0].length; col++)
            {
                if(faces[row][col] != null)
                {
                    faces[row][col].drawSelf(row, col);
                }
            }
        }
    }
    
    public void mousePressed()
    {
        final int row = getRow(mouseY);
        final int col = getColumn(mouseX);
        
        if(row != -1 && col != -1)
        {
            if(faces[row][col] == null)
            {
                faces[row][col] = new Face(this);
            }
            else if( ! faces[row][col].isSad() )
            {
                faces[row][col].makeSad();
            }
            else
            {
                faces[row][col] = null;
            }
            
            redraw();
        }
    }
    
    // returns row corresponding to y or -1 if not an existing row
    public int getRow(int y)
    {
        if(y < getTopY(0) || y >= getTopY(ROWS))
            return -1;
        
        return (y - TOP_OFFSET) / BOX_HEIGHT;
    }
    
    // returns column corresponding to x or -1 if not an existing column
    public int getColumn(int x)
    {
        if(x < getLeftX(0) || x >= getLeftX(COLUMNS))
            return -1;
        
        return (x - LEFT_OFFSET) / BOX_WIDTH;
    }
    
    public int getTopY(int row)
    {
        return TOP_OFFSET + (row * BOX_HEIGHT);
    }
    
    public int getLeftX(int column)
    {
        return LEFT_OFFSET + (column * BOX_WIDTH);
    }
    
    public void drawGrid()
    {
        rectMode(CORNER);
        noFill();
        strokeWeight(1);
        stroke(255);
        
        for(int row = 0; row < ROWS; row++)
        {
            for(int col = 0; col < COLUMNS; col++)
            {
                rect(getLeftX(col), getTopY(row), BOX_WIDTH, BOX_HEIGHT);
            }
        }
    }
}
