package secondswing;

/**
 * Title:
 * Description:
 * Copyright:    Copyright (c) 2002
 * Company:
 * @author Burton Rosenberg
 * @version 9 April 2002 [creation date: 9 April 2002]
 */

import java.awt.* ;
import java.awt.event.* ;

// responds to Events and Updates model, as a Controller should.
// Also implements the Model, and is asked by the View for the
// Model's colors and shapes.

class MyController implements ActionListener {

    MyView mv ;
    int colorIndex = 0 ;

    Color [][] colorArray = {
       { Color.red, Color.white, Color.blue },
       { Color.pink, Color.black, Color.cyan } ,
       { Color.orange, Color.yellow, Color.magenta }
       } ;

  // blue square is 3x3 (in bar-height).
  // flag is 5x6 (in bar-height)

  // each entry in RECTANGLE is ( x-org, y-org, width, height )
  // in units of BAR_HEIGHT, and (x-org, y-org) is relative
  // to (X_ORG, Y_ORG)

  private static final int [][][] ALL_RECTANGLES = {
     { { 3,0,4,1 }, { 3,2,4,1 }, { 0,4,7,1 } }, // red rectangles
     { { 3,1,4,1  }, { 0,3,7,1 } },             // white rectangles
     { { 0,0,3,3  } }                           // blue rectangles
     } ;

    void setView( MyView mv ) {
       this.mv = mv ;
    }

    // these next two methods are synchronized so as to share
    // colorIndex between two threads: the graphic redraw thread
    // which calls currentColors and the event thread which calls
    // nextColor (via actionPerformed)

    // [ed: although, this is gratuitous here, since the access of colorIndex
    // is most likely atomic.]

    synchronized Color [] currentColors() {
       return colorArray[colorIndex] ;
    }

    synchronized void nextColor() {
       colorIndex = (colorIndex+1)%colorArray.length ;
    }

    int [][][] currentRectangles() {
       return ALL_RECTANGLES ;
    }

    // implement ActionListener
    public void actionPerformed(ActionEvent ae) {
       nextColor() ;
       mv.repaint();   // tell system to repaint view when convenient
    }

}
