import java.io.*;


/**
 * The Controller for a garage door opener
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 0.1
 */
public class Controller
{
    private BufferedReader          in;    
    private PrintWriter             out;    
    private int                     state;

    private static final int        AWAITING_COMBINATION = 0;
    private static final int        CLOSED               = 1;
    private static final int        LOCKED               = 2;
    private static final int        OPENED               = 3;
    


    
    /**
     * Explicit Value Constructor
     *
     * @param is  The InputStream used for input and output
     * @param os  The OutputStream used for input and output
     */
    public Controller(InputStream is, OutputStream os) throws IOException
    {
       in  = new BufferedReader(new InputStreamReader(is));
       out = new PrintWriter(os);

       setState(CLOSED);
    }


    

    /**
     * Run this controller (i.e., prompt the user to enter
     * a command and respond accordingly)
     */
    public void run() throws IOException
    {
       String           line;
       
       out.print("Command (close,combination,error,lock,open,unlock): ");  
       out.flush();
       
       while ((line=in.readLine()) != null)
       {
          if (line.equals("close"))
          {
             if (state == OPENED) setState(CLOSED);             
          }
          if (line.equals("combination"))
          {
             if (state == AWAITING_COMBINATION) setState(CLOSED);             
          }
          if (line.equals("error"))
          {
             if (state == AWAITING_COMBINATION) setState(LOCKED);             
          }
          if (line.equals("lock"))
          {
             if (state == CLOSED) setState(LOCKED);             
          }
          if (line.equals("open"))       
          {
             if (state == CLOSED) setState(OPENED);             
          }
          if (line.equals("unlock"))     
          {
             if (state == LOCKED) setState(AWAITING_COMBINATION);             
          }
          
          out.print("Command (close,combination,error,lock,open,unlock): "); 
          out.flush();
       }
    }



    /**
     * Set the state
     *
     * @param state    The new state
     */
    private void setState(int state)
    {
       this.state = state;
       out.println("  State set to: "+state);
       out.flush();       
    }
    
}

