/*
   Filename: MDICraps
   Used by:  MDIGridBag.java

This file is based on Deitel's Craps class,
modified so that:

a. Each time an instance of MDICraps is created, the MDICraps
   instance creates its own JFrame to display itself within.

b. MDICraps expects to be created with a reference to an
   invoking class of type MDIGridBag, and uses this reference
   when the MDICraps SendBankRollToCreator JButton is pressed.

*/


//22
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*; // for file I/O

public class MDICraps extends JFrame implements ActionListener, WindowListener {

// constant variables for status of game
   final int WON = 0, LOST = 1, CONTINUE = 2;

   // other variables used in program
   boolean firstRoll = true;   // true if first roll
   int sumOfDice = 0;          // sum of the dice
   int myPoint = 0;   // sets point if no win/loss on first roll
   int gameStatus = CONTINUE;  // game not over yet
   int bankRoll = 50;          // start with $50 bankroll
   private static final long serialVersionUID = 1L;

   // graphical user interface components
   JLabel die1Label, die2Label, sumLabel, pointLabel, gameResultLabel;
   JTextField firstDie, secondDie, sum, point, gameResult;
   JButton roll;

   JLabel bankRollLabel;
   JTextField bankRollText;
   JButton save;
   MDIGridBag creator;
   JButton sendToCreatorButton;
   // output file
   BufferedWriter outFile;

   // setup graphical user interface components
 //  public void init()
public MDICraps(MDIGridBag creatorLink)
   {
       creator = creatorLink; // link for comm with caller
       // new standalone frame to display components in
       JFrame frame = new JFrame("Craps Game");
       Container c = frame.getContentPane();
       c.setLayout( new FlowLayout() );

      die1Label = new JLabel( "Die 1" );
      c.add( die1Label );
      firstDie = new JTextField( 10 );
      firstDie.setEditable( false );
      c.add( firstDie );

      die2Label = new JLabel( "Die 2" );
      c.add( die2Label );
      secondDie = new JTextField( 10 );
      secondDie.setEditable( false );
      c.add( secondDie );

      sumLabel = new JLabel( "Sum is" );
      c.add( sumLabel );
      sum = new JTextField( 10 );
      sum.setEditable( false );
      c.add( sum );

      pointLabel = new JLabel( "Point is" );
      c.add( pointLabel );
      point = new JTextField( 10 );
      point.setEditable( false );
      c.add( point );

      roll = new JButton( "Roll Dice" );
      roll.addActionListener( this );
      c.add( roll );

      // save to file
      save = new JButton( "Save Bankroll to file" );
      save.addActionListener( this );
      c.add( save );

      sendToCreatorButton = new JButton( "Send Bankroll to Creator" );
      sendToCreatorButton.addActionListener( this );
      c.add( sendToCreatorButton );


      bankRollLabel = new JLabel( "Bankroll" );
      c.add( bankRollLabel );
      bankRollText = new JTextField( 10 );
      bankRollText.setEditable( false );
      c.add( bankRollText );
      bankRollText.setText(Integer.toString(bankRoll));

      gameResultLabel = new JLabel( "Game Status" );
      c.add( gameResultLabel );
      gameResult = new JTextField( 30 );
      gameResult.setEditable( false );
      c.add( gameResult );
      gameResult.setText("Click Roll Dice to play.");
     
      // sets up for handling closing of JFrames when user clicks close X
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.addWindowListener(this);

      frame.setSize(400,200);
      frame.setVisible(true); 

   } // end init


    public void windowActivated(WindowEvent e){}; 
    public void windowClosed(WindowEvent e){  // What to do when user closes JFrame   
      JOptionPane.showMessageDialog(null,
         "I see that you closed this Craps Game instance.");
    }; 
    public void windowClosing(WindowEvent e){}; 
    public void windowDeactivated(WindowEvent e){}; 
    public void windowDeiconified(WindowEvent e){}; 
    public void windowIconified(WindowEvent e){}; 
    public void windowOpened(WindowEvent e){};

   // call method play when button is pressed
   public void actionPerformed( ActionEvent e )
   {
      // choose what action to perform based on the source
      // of the ActionEvent

      if (e.getSource() == roll){          
          play();
      }

      if (e.getSource() == save){
          saveBankRollToFile();
          roll.setEnabled(true);
      }
      if (e.getSource() == sendToCreatorButton){
           creator.addToCrapsTotal(bankRoll);
           bankRoll = 0;
           bankRollText.setText(Integer.toString(bankRoll));
           sendToCreatorButton.setEnabled(false); // only allows 1 use of send button
           gameResult.setText("Notice that the \"Send Bankroll ...\" button has been disabled.");
      }
   }

  // save value of bankroll to file
  public void saveBankRollToFile(){

       String outputFileName = new String("bankroll.txt");

      // erases prior contents of file and writes current bankroll amount
  try {
      outFile = new BufferedWriter(new FileWriter(outputFileName));
    } // end try

    catch (IOException e) {
       System.out.println("IO Problem!");
       e.printStackTrace();
    }  // end catch

    try {
        outFile.write(String.valueOf(bankRoll));
        gameResult.setText("Bankroll written to bankroll.txt.");
        outFile.close();
    } // end try
    catch (IOException e){
       System.out.println(e.toString());
    } // end catch

  } // end openFiles


   // process one roll of the dice
   public void play() {

      if ( firstRoll ) {             // first roll of the dice
         sumOfDice = rollDice();

         switch ( sumOfDice ) {
            case 7: case 11:         // win on first roll
               gameStatus = WON;
               point.setText( "" );  // clear point text field
               break;
            case 2: case 3: case 12: // lose on first roll
               gameStatus = LOST;
               point.setText( "" );  // clear point text field
               break;
            default:                 // remember point
               gameStatus = CONTINUE;
               myPoint = sumOfDice;
               point.setText( Integer.toString( myPoint ) );
               firstRoll = false;
               break;
         }
      }
      else {   // not first roll
         sumOfDice = rollDice();

         if ( sumOfDice == myPoint ) {   // win by making point
            gameStatus = WON;
         }
         else
            if ( sumOfDice == 7 ) {      // lose by rolling 7
               gameStatus = LOST;
            }
      }


      if ( gameStatus == CONTINUE ){

         gameResult.setText( "Click Roll Dice again to continue play." );

         }
      else {
         if ( gameStatus == WON ) {

         gameResult.setText( "Player wins. " +
               "Click Roll Dice to play again." );
            bankRoll += 5;
         }
         else {

          gameResult.setText( "Player loses. " +
               "Click Roll Dice to play again." );
            bankRoll -= 5;
         }

         firstRoll = true;

         bankRollText.setText(Integer.toString(bankRoll));
      }

   }

   // roll the dice
   public int rollDice()
   {
      int die1, die2, workSum;

      die1 = 1 + ( int ) ( Math.random() * 6 );
      die2 = 1 + ( int ) ( Math.random() * 6 );
      workSum = die1 + die2;
       // display new values to TextFields in content pane
      firstDie.setText( Integer.toString( die1 ) );
      secondDie.setText( Integer.toString( die2 ) );
      sum.setText( Integer.toString( workSum ) );
      bankRollText.setText(Integer.toString(bankRoll));

      return workSum;
   }
}

