/*
 * @(#)JavaScriptMaker.java
 *
 * Copyright (C) 2002-2003 Matt Albrecht
 * groboclown@users.sourceforge.net
 * http://groboutils.sourceforge.net
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the 
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software. 
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL 
 *  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 *  DEALINGS IN THE SOFTWARE.
 */

package net.sourceforge.groboutils.uicapture.v1.javamaker;

import net.sourceforge.groboutils.uicapture.v1.VirtualWindowController;
import net.sourceforge.groboutils.uicapture.v1.IScriptMaker;

import java.io.Writer;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.File;


/**
 * Creates a Java playback sourcefile.  The Java file will quit with an error
 * code of 1 if the playback did not go perfectly.
 *
 * @author    Matt Albrecht <a href="mailto:groboclown@users.sourceforge.net">groboclown@users.sourceforge.net</a>
 * @version   Jan 7, 2002
 */
public class JavaMaker implements IScriptMaker
{
    private Writer outF = null;
    private PrintWriter out = null;
    private String packageName = null;
    private String className = null;
    private int step = 0;
    
    
    public JavaMaker( File outFile, String packageName, String className )
            throws IOException
    {
        if (outFile == null || packageName == null || className == null)
        {
            throw new IllegalArgumentException( "no null args" );
        }
        this.outF = new FileWriter( outFile );
        this.out = new PrintWriter( outF );
        
        this.packageName = packageName;
        this.className = className;
    }
    
    
    public JavaMaker( Writer w, String packageName, String className )
    {
        if (w == null || packageName == null || className == null)
        {
            throw new IllegalArgumentException( "no null args" );
        }
        this.outF = w;
        this.out = new PrintWriter( w );
        
        this.packageName = packageName;
        this.className = className;
    }
    
    
    //-------------------------------------------------------------------------
    // Public methods

    /**
     * Starts the script generation.
     */
    public void start()
    {
        if (this.step > 0)
        {
            throw new IllegalStateException("Already started generation.");
        }
        
        wrln( "/"+"*" );
        wrln( " * Pregenerated script file." );
        wrln( " * Created "+(new java.util.Date()).toString() );
        wrln( " *"+"/" );
        wrln();
        wrln( "package "+this.packageName+";" );
        wrln();
        wrln( "import "+VirtualWindowController.class.getName()+";" );
        wrln( "import "+File.class.getName()+";" );
        wrln();
        wrln( "public class "+this.className );
        wrln( "{" );
        wrln( "    public static void main( String[] args )" );
        wrln( "            throws Exception" );
        wrln( "    {" );
        step( "Setup." );
        wrln( "        VirtualWindowController vwc = new " );
        wrln( "	           VirtualWindowController();" );
        wrln( "        vwc.begin();" );
        wrln( "      try {" );
        wrln( "        vwc.sleep( 2000 );" );
        
        // bug 618295
        this.step = 1;
    }
    
    
    /**
     * Terminates the script generation.
     */
    public void end()
    {
        assertActive();
        
        wrln( "        /"+"/ end of script" );
        wrln( "        System.out.println( \"No errors found in playback.\" ):");
        wrln( "        System.exit( 0 );" );
        wrln( "      } finally {" );
        wrln( "        vwc.end();" );
        wrln( "        vwc = null;" );
        wrln( "      }" );
        wrln( "    }" );
        wrln( "}" );
        
        // bug 618295
        this.step = 2;
        
        try
        {
            this.out.close();
            this.outF.close();
        }
        catch (IOException ioe)
        {
            handleException( ioe );
        }
        finally
        {
            this.out = null;
            this.outF = null;
        }
    }
    
    
    /**
     * Cause the script to delay for the given number of milliseconds.
     */
    public void generateDelay( long milliseconds )
    {
        assertActive();
        
        step( "sleep for "+milliseconds+" milliseconds." );
        wrln( "        vwc.sleep( "+milliseconds+" );" );
    }

    
    /**
     * Cause the script to rotate the mouse wheel.
     */
    public void generateMoveMouseWheel( int rotate )
    {
        assertActive();
        
        step( "rotate mouse wheel "+rotate+" clicks." );
        wrln( "        vwc.moveMouseWheel( "+rotate+" );" );
    }

    
    /**
     * Cause the script to move the mouse.
     */
    public void generateMoveMouse( int x, int y )
    {
        assertActive();
        
        step( "move mouse to ("+x+", "+y+")." );
        wrln( "        vwc.moveMouse( "+x+", "+y+" );" );
    }

    
    /**
     * Cause the script to press a mouse button.
     */
    public void generatePressMouse( int modifier )
    {
        assertActive();
        
        step( "press mouse with "+modifier+"." );
        wrln( "        vwc.pressMouse( "+modifier+" );" );
    }

    
    /**
     * Cause the script to release a mouse button.
     */
    public void generateReleaseMouse( int modifier )
    {
        assertActive();
        
        step( "release mouse with "+modifier+"." );
        wrln( "        vwc.releaseMouse( "+modifier+" );" );
    }

    
    /**
     * Cause the script to press a key.
     */
    public void generatePressKey( int keyCode )
    {
        assertActive();
        
        step( "press key with "+keyCode+"." );
        wrln( "        vwc.pressKey( "+keyCode+" );" );
    }

    
    /**
     * Cause the script to release a key.
     */
    public void generateReleaseKey( int keyCode )
    {
        assertActive();
        
        step( "release key with "+keyCode+"." );
        wrln( "        vwc.releaseKey( "+keyCode+" );" );
    }

    
    /**
     * Cause the script to capture a screen shot.  Probably, it should compare
     * the captured image against the original saved image.
     *
     * @param x screen image bounds.
     * @param y screen image bounds.
     * @param width screen image bounds.
     * @param height screen image bounds.
     */
    public void generateScreenCapture( File originalImage,
            int x, int y, int width, int height )
    {
        assertActive();
        
        step( "capture and compare screen in ("+x+", "+y+", "+width+", "+
            height+" ) against "+originalImage+"." );
        wrln( "        File f"+this.step+" = new File( \""+
            className + "-" + this.step + ".\" + vwc.getImageExtension() );" );
        wrln( "        vwc.saveScreenImage( f"+this.step+".toString(), "+x+
            ", "+y+", "+width+", "+height+" );" );
        wrln( "        if (!vwc.compareFiles( f"+step+", new File( \"" +
            originalImage + "\" ))" );
        wrln( "        {" );
        wrln( "            System.out.println( \"Images did not match on step "+
            this.step+".\" );" );
        wrln( "            System.out.println( \"Test Failed.\" );" );
        wrln( "            vwc.end();" );
        wrln( "            vwc = null;" );
        wrln( "            Thread.sleep( 1000 );" );
        wrln( "            System.exit(1);" );
        wrln( "        }" );
        wrln( "        System.out.println( \"** Images match!\" );");
    }
    
    
    //-------------------------------------------------------------------------
    
    protected void handleException( Throwable t )
    {
        t.printStackTrace();
        this.out = null;
        this.outF = null;
        throw new IllegalStateException("Encountered exception "+t);
    }
    
    protected void assertActive()
    {
        if (this.out == null)
        {
            throw new IllegalStateException("Not open for writing.");
        }
        if (this.step <= 0)
        {
            throw new IllegalStateException("Never started writing.");
        }
    }
    
    
    protected void wr( String text )
    {
        this.out.print( text );
    }
    protected void wrln( String text )
    {
        this.out.println( text );
    }
    protected void wrln()
    {
        this.out.println( "" );
    }
    
    
    protected void step( String msg )
    {
        ++this.step;
        wrln( "        System.out.println( \"Step "+this.step+": "+
            msg +"\" );" );
    }
}

