import java.io.*;
import com.swath.*;
import com.swath.cmd.*;

/**
 * Probe exploration script for SWATH.  Reads list of target sectors
 * from a text file.  Automatic or interactive probing, automatic
 * restocking of probes when used at Stardock, automatic marking of
 * avoids when probes encounter enemy fighters.  In interactive mode,
 * displays the route to each target sector and lets the user decide
 * whether to probe the route or move on to the next target.
 *
 * <p>2.0 CHANGES:<br>
 * Detects intercepted probes and marks avoids.  Allows the user to
 * begin probing from a specified line in the target list and reports
 * "restart line" when interrupted.  The API does not detect when a
 * probe is destroyed at its destination, so keep your eyes on the
 * screen!  [Note: LaunchEtherProbe.exec() hangs when a probe is
 * destroyed, so this script is effectively broken.]
 *
 * <p>1.1 CHANGES:<br>
 * Remembers target list filename between runs.  Fixed a minor bug
 * which may not have ever existed.
 *
 * <p>Bug reports to: krum@oco.net
 *
 * @author Mongoose
 * @version 2.0, 28 July 2001
 */
public class ProbeHunter2 extends UserDefinedScript {

        protected Parameter fileNameP;
        protected Parameter restartLineP;
        protected Parameter autoP;
        protected static String fileName = "eprobe.txt";
        /* 1-based because most text editors show line numbers this way */
        protected static int restartLine = 1;
        protected static final String title = "Probe Hunter";
        protected static final String error = "Script Error";
        int probesLaunched = 0; /* for statistics */
        int targetsReached = 0;

public String getName() { return title; }

public boolean initScript() throws Exception {
        /* check prompt */
        if(!atPrompt(Swath.COMMAND_PROMPT)) {
                MessageBox.exec("You must be at the command prompt.",
                        error,
                        MessageBox.ICON_ERROR,
                        MessageBox.TYPE_OK);
                        return false;
        }

        fileNameP = new Parameter("Target file:");
        fileNameP.setType(Parameter.STRING);
        fileNameP.setString(fileName);

        restartLineP = new Parameter("Start at line:");
        restartLineP.setType(Parameter.INTEGER);
        restartLineP.setInteger(restartLine);

        autoP = new Parameter("Auto probe?");
        autoP.setType(Parameter.BOOLEAN);
        autoP.setBoolean(false);

        registerParam(fileNameP);
        registerParam(restartLineP);
        registerParam(autoP);

        return true;
}

public boolean runScript() throws Exception {

        /* The detailed error handling is to help me identify
        any bugs which may arise from unforeseen usage. */

        String line = "";
        int currentLine = 0; /* line num of last line read */
        int target = 0;
        int reached = 0;        /* scratch var for where probe got to */
        int sectors = Swath.main.sectors();
        boolean auto = autoP.getBoolean();
        BufferedReader targetList;

        /* refresh info, force wait so swath will notice */
        SendString.exec("i");
        WaitForText.exec("Trader Name");
        while(!atPrompt(Swath.COMMAND_PROMPT)) Thread.sleep(200);
        /* if you have no probes, and are either not at stardock or broke... */
        if(Swath.ship.etherProbes() == 0 &&
        (Swath.main.currSector() != Swath.main.stardock() ||
        Swath.you.credits() < 3000)) {
                MessageBox.exec("You have no probes!",
                        error,
                        MessageBox.ICON_ERROR,
                        MessageBox.TYPE_OK);
                return false;
        }

        /* set up file reader */
        fileName = fileNameP.getString();
        try {
                targetList = new BufferedReader(new FileReader(fileName));
        } catch(FileNotFoundException e) {
                MessageBox.exec("Target file does not exist.",
                        error,
                        MessageBox.ICON_ERROR,
                        MessageBox.TYPE_OK);
                return false;
        } catch(IOException e) {
                MessageBox.exec("Error opening target file.",
                        error,
                        MessageBox.ICON_ERROR,
                        MessageBox.TYPE_OK);
                return false;
        }

        restartLine = restartLineP.getInteger();

        nextTarget: while(targetList.ready()) {
                /* get the next line from the target list */

                try { line = targetList.readLine(); }
                catch(IOException e) {
                        MessageBox.exec("Error reading from target list.",
                                error,
                                MessageBox.ICON_ERROR,
                                MessageBox.TYPE_OK);
                        return true;
                }
                ++currentLine;
                if(currentLine < restartLine) continue;
                /* parse the line */
                try { target = Integer.parseInt(line); }
                catch(NumberFormatException e) { continue; }
                /* validate the target */
                if(target <= 0 || target > sectors) continue;
                /* save current line for later */
                restartLine = currentLine;

                /* keep probing until target is reached; the test to get
                out of this loop is at the end, around line 190. */
                reached = 0;
                while(true) {
                        /* display path to target */
                        if(!auto) {
                                SendString.exec("c");
                                WaitForText.exec("Computer command [TL=");
                                SendString.exec("f\r" + target + "\rq");
                                while(!atPrompt(Swath.COMMAND_PROMPT)) Thread.sleep(200);
                                switch(MessageBox.exec("Shoot this path?",
                                        title,
                                        MessageBox.ICON_QUESTION,
                                        MessageBox.TYPE_YES_NO_CANCEL)) {

                                        case MessageBox.RES_YES:
                                                break; /* from switch */

                                        case MessageBox.RES_NO:
                                                continue nextTarget;

                                        case MessageBox.RES_CANCEL:
                                                return true;
                                }
                        }
                        /* check probes, buy more if needed */
                        if(Swath.ship.etherProbes() == 0) {
                                if(Swath.main.currSector() == Swath.main.stardock() &&
                                Swath.you.credits() >= 3000) {
                                        if(auto) buyProbes();
                                        else if(MessageBox.exec("Out of probes. Buy more?",
                                                title,
                                                MessageBox.ICON_QUESTION,
                                                MessageBox.TYPE_YES_NO) == MessageBox.RES_YES)

                                                        buyProbes();
                                        else return true;
                                } else {
                                        MessageBox.exec("Out of probes.",
                                                error,
                                                MessageBox.ICON_ERROR,
                                                MessageBox.TYPE_OK);
                                        return true;
                                }
                        }

                        reached = LaunchEtherProbe.exec(target);
                        ++probesLaunched;

                        if(reached == target) {
                                ++targetsReached;
                                break;
                        } else {
                                SendString.exec("cv" + reached + "\rq");
                                /* continue */
                        }
                }
        }
        return true;
}

public void endScript(boolean finished) {
        if(finished) try {
        MessageBox.exec(probesLaunched + " probes launched, " + targetsReached + " targets reached.\n" +
                "Restart at line " + restartLine + " of " + fileName + '.',
                title,
                MessageBox.ICON_INFORMATION,
                MessageBox.TYPE_OK);
        } catch(Exception e) { /* ignore */ }
}

protected void buyProbes() throws Exception {
        SendString.exec("ps");
        WaitForText.exec("<StarDock> Where to? (?=Help)");
        SendString.exec("he");
        String line = WaitForText.exec("How many Probes do you want (Max");
        /* buy max, blast off, and refresh info */
        SendString.exec(line.substring(33, line.indexOf(')')) + "\rqqi");
        /* wait for prompt */
        while(!atPrompt(Swath.COMMAND_PROMPT)) Thread.sleep(200);
}

} /* end class ProbeHunter2 */
