
// ColorsGrid.java   (was Tutorial03.java)
// Martin Berglund
// Modified by Andrew Davison, ad@coe.psu.ac.th, March 2023

/* Creates a screenful of randomly colored cells that keep changing
   color. There's also a message box in the top-left corner that
   reports the current terminal size.

   The code responds to terminal size changes by drawing more
   or less cells, and reporting the new size in the message box.

   Uses Lanterna 3
   https://github.com/mabe02/lanterna

   More info at:
  https://github.com/mabe02/lanterna/blob/master/docs/using-screen.md

   Usage (Windows):
     > compile.bat ColorsGrid.java
     > run.bat ColorsGrid

   Usage (Linux):
     > ./compile.sh ColorsGrid.java
     > ./run.sh ColorsGrid

*/


import java.io.*;
import java.util.*;

import com.googlecode.lanterna.*;
import com.googlecode.lanterna.input.*;
import com.googlecode.lanterna.screen.*;
import com.googlecode.lanterna.terminal.*;


public class ColorsGrid
{
  private static Random rand = new Random();


  public static void main(String[] args)
                         //       throws IOException
  {
    Screen scr = Utils.createScreen();
    scr.setCursorPosition(null);   // hides the cursor

    TerminalSize termSz = scr.getTerminalSize();
    System.err.println("Terminal size: " + termSz);

    // generate a grid of random colors
    for(int col = 0; col < termSz.getColumns(); col++)
      for(int row = 0; row < termSz.getRows(); row++)
        Utils.setCell(scr, col, row, Utils.randomColor());
    Utils.refresh(scr);

    // keep modifying the screen
    while (true) {
      KeyStroke ks = Utils.pollInput(scr);
      if (Utils.hasQuit(ks))
        break;

      // check if the terminal has been resized
      TerminalSize nSize = scr.doResizeIfNecessary();
      if (nSize != null) {
        termSz = nSize;
        System.err.println("Terminal size: " + termSz);
      }

      changeCells(scr, termSz, 80);  // change 80 random cells
      Utils.messageBox(scr, "Terminal Size: " + termSz, 1, 1);

      Utils.refresh(scr);
      Utils.pause(100);
    }

    Utils.close(scr);
  } /* main */



  private static void changeCells(Screen scr, 
                       TerminalSize termSz, int numCells)
  {
    int numCols = termSz.getColumns();
    int numRows = termSz.getRows();
    for (int i = 0; i < numCells; i++) {
      int col = rand.nextInt(numCols);
      int row = rand.nextInt(numRows);
      Utils.setCell(scr, col, row, Utils.randomColor());
    }
  } // end of changeCells()


} // end of ColorsGrid class
