import org.postgresql.core.v3.QueryExecutorImpl;

import java.io.*;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

public class ParserSpeedTest {

    List queries;

    public ParserSpeedTest(List queries) {
        this.queries = queries;
    }

    public void run(int count)
    {
        QueryExecutorImpl q = new QueryExecutorImpl(null, null,
                new Properties(), null);
        for (int c = 0; c < count; ++c)
        {
            for (Iterator i = queries.iterator(); i.hasNext();)
            {
                String query = (String) i.next();
                q.createSimpleQuery(query);
            }
        }
    }

    public static void main(String[] args)
    {
        List queries = new LinkedList();

        if (args.length < 2)
        {
            System.out.println("Usage: java ParserSpeedTest count file.sql,...");
            System.exit(1);
        }

        int count = 1;
        
        try
        {
            count = Integer.parseInt(args[0]);
            
            for (int i = 1; i < args.length; i++)
            {
                String fname = args[i];
                File file = new File(fname);
                if (!file.exists() || !file.canRead())
                {
                    System.err.println("Argument \"" + fname
                            + "\" is not a valid file name");
                }

                StringWriter w = new StringWriter();
                Reader r = new FileReader(file);
                char[] buf = new char[2048];
                for (int read; (read = r.read(buf)) > 0;)
                {
                    w.write(buf, 0, read);
                }
                queries.add(w.getBuffer().toString());
            }
        } catch (IOException e)
        {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
            System.exit(1);
        }
        catch (NumberFormatException e)
        {
            System.err.println("First argument must be a number: " + args[0]);
            System.exit(1);
        }

        ParserSpeedTest test = new ParserSpeedTest(queries);
        long start = System.currentTimeMillis();
        test.run(count);
        long end = System.currentTimeMillis();
        long total = end - start;
        double time = ((double)total) / 1000;

        System.out.println("Files: " + queries.size() + "  Runs: " + count);
        System.out.println("Time: "
                + new BigDecimal(time).setScale(3, BigDecimal.ROUND_HALF_UP)
                + " s");

    }
}
