package tmcsim.cadsimulator;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import static tmcsim.cadsimulator.CADSimulatorFixture.bos;

/**
 * Note: This test requires an internet connection, for building data files from
 * a master copy at pastebin.
 *
 * @author jdalbey
 */
public class CADSimulatorFixture
{

    static CADSimulator app;
    static ByteArrayOutputStream bos;
    static PrintStream ps;
    static final String configData =
            "CADClientPort          = 4444 \n"
            + "CoordinatorRMIPort     = 4445 \n"
            + "CADRmiPort             = 4446 \n"
            + "UserInterface          = tmcsim.cadsimulator.viewer.CADConsoleViewer\n"
            + "ParamicsProperties     = pconfig.txt\n"
            + "ATMSProperties         = empty.txt\n"
            + "MediaProperties        = empty.txt\n";
    static final String paramicsData = "ParamicsCommHost       = 192.168.251.45\n"
            + "ParamicsCommPort       = 4450\n"
            + "IncidentUpdateInterval = 30\n"
            + "IncidentUpdateFile     = exchange.xml\n"
            + "ParamicsStatusInterval = 15\n"
            + "ParamicsStatusFile     = paramics_status.xml\n"
            + "CameraStatusInterval   = 30\n"
            + "CameraStatusFile       = camera_status.xml\n";
    static final String paramConfig    = "SocketPort=4450\n"
            +"WorkingDirectory=.\nGUIvisible=false";
    static final String cardfileURL = "http://pastebin.com/raw/Yr26nfp7";
    static final String smallXMLURL = "http://pastebin.com/raw/Eqj2N5qD";
    /*
     * Creating instance of app must be done only once or you get registry
     * bind problems, and code Written in Constructor is Executed
     * before each Test Method
     */

    public static void writeConfigData()
    {
        // Declare a stream to the output
        bos = new ByteArrayOutputStream();
        ps = new PrintStream(bos);
        // Redirect the standard output
        System.setOut(ps);
        writedata("config.txt", configData);
        writedata("pconfig.txt", paramicsData);
        writedata("empty.txt", "");
        writeScriptfiles();
    }

    public static void writeScriptfiles()
    {
        writeFileFromURL("scripts/Cardfile.xml", cardfileURL);
        writeFileFromURL("scripts/one-incident.xml", smallXMLURL);
    }

    private static void writeFileFromURL(String filename, String urlstring)
    {
        File cardFile = new File(filename);
        // If a cardfile exists, leave it
        if (!cardFile.exists())
        {
            // if cardfile doesn't exist, copy from our special pastebin
            java.io.File dir = new java.io.File("scripts");
            dir.mkdir();
            URL url = null;
            try
            {
                url = new URL(urlstring);
            } catch (MalformedURLException ex)
            {
                Logger.getLogger(CADSimulatorFixture.class.getName()).log(Level.SEVERE, null, ex);
            }
            try
            {
                Scanner in = null;
                in = new Scanner(url.openStream()).useDelimiter("\\A");
                String out = in.next();
                writedata(filename, out);
            } catch (IOException ex)
            {
                Logger.getLogger(CADSimulatorFixture.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void startCADSim()
    {
        // This will set the desired property as long as you don't call the main() method.
        System.setProperty("CAD_SIM_PROPERTIES", "config.txt");
        if (System.getProperty("CAD_SIM_PROPERTIES") != null)
        {
            try
            {
                app = new CADSimulator(System.getProperty("CAD_SIM_PROPERTIES"));
            } catch (Exception ex)
            {
                ex.printStackTrace();
                junit.framework.TestCase.fail("Couldn't launch CADSimulator");
            }
        } else
        {
            junit.framework.TestCase.fail("CAD_SIM_PROPERTIES system property not defined.");
        }
    }
    // Write the test data to a file

    public static void writedata(String filename, String data)
    {
        PrintWriter writer = null;
        try
        {
            writer = new PrintWriter(new FileWriter(filename));
            writer.println(data);
            writer.close();
        } catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }

    public static void pause(int millis)
    {
        try
        {
            Thread.sleep(millis);
        } catch (InterruptedException ex)
        {
            ex.printStackTrace();
        }
    }
}
