/*
 * Created on Mar 3, 2004
 */
package org.lucci.madhoc.script;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Date;
import java.util.Collections;
import java.util.List;
import java.util.Vector;

import org.lucci.madhoc.Version;
import org.lucci.math.relation.Function;
import org.lucci.math.relation.NumericFunction;
import org.lucci.text.TextUtilities;

/**
 * @author luc.hogie
 */
public class Batch
{
    private int verboseLevel = 0;
    
    
    public Batch()
    {
//      System.out.println("Madhoc (release \"" + Madhoc.RELEASE + "\")\n");
    }
    
    
    private long lastDate = -1;
    
    public void println(PrintStream stream, String s, int level)
    {
        if (level >= getVerboseLevel())
        {
            stream.println(getDate() + " - " + s);
        }
    }

    public void println(String s, int level)
    {
        println(System.out, s, level);
    }

    public void println(String s)
    {
        println(System.out, s, 1);
    }
    
    public File getDataFile(String[] parms, File directory)
    {
        String s = directory.getAbsolutePath();
        
        for (int i = 0; i < parms.length; ++i)
        {
            s += '/' + normalize(parms[i]);
        }
    
        s += ".txt";
        return new File(s);
    }
    
    public String normalize(String s)
    {
        return s.replaceAll(" ", "_"); 
    }
    
    
    /**
     * Save the values of the given function in the given file.
     * Because this is to be used by time consuming simulation,
     * in case the file cannot be written, no exeption is launched
     * but the text is written (with a warning) on the standard output.
     */
    public void saveFunctionToFile(NumericFunction f, File dataFile)
    {
        dataFile.getParentFile().mkdirs();
        
        List keys = new Vector(f.getKeys());
        Collections.sort(keys);
        String text = f.getGNUPlotText(keys);

        if (text.length() == 0)
            println("\nWarning!!! \"" + dataFile.getAbsolutePath() + "\" will not contain any data\n");

        try
        {
            FileOutputStream fos = new FileOutputStream(dataFile);
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bos.write(text.getBytes());
            bos.flush();
            bos.close();
            fos.flush();
            fos.close();
        }
        catch (IOException ex)
        {
            println("\nWarning!!! I/O error while attempting to write \"" + dataFile.getAbsolutePath() + "\"\n. Here is the text to write:\n");
            println(text);
            println("\n");
        }
    }
    

    /**
     * Returns the current time in a string form. This should be used
     * by the simulation batch process to indicate the time of the
     * different steps.
     * @return
     */
    private String getDate()
    {
        long currentDate = System.currentTimeMillis();
        Date date = new Date(currentDate);
        String s = date.toLocaleString();
        int durationLenght = 18;
        
        if (lastDate == -1)
        {
            s += TextUtilities.repeat(" ", durationLenght);
        }
        else
        {
            long duration = currentDate - lastDate;
            s += TextUtilities.flushRight("(" + duration + "ms later)", durationLenght, ' ');
        }

        lastDate = currentDate;
        return s; 
    }
    
    public String getHostName()
    {
        try
        {
            return InetAddress.getLocalHost().getHostName();
        }
        catch (UnknownHostException e)
        {
            throw new IllegalStateException();
        }
    }

    public int getVerboseLevel()
    {
        return verboseLevel;
    }
    public void setVerboseLevel(int verboseLevel)
    {
        this.verboseLevel = verboseLevel;
    }
}