package com.queplix.installer;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author dmitry.antonov
 */
public class ToolsProcessor {

    private static int paramNmb = 0;
    private static boolean firstTimeConnection = true;

    private static void addRequestParam(StringBuffer sb, String paramName, String paramValue) {
        if (paramNmb++ == 0) {
            sb.append('?');
        }
        else {
            sb.append('&');
        }
        sb.append(paramName);
        sb.append('=');
        sb.append(paramValue.replaceAll(" ", "%20"));
    }

    private static HttpURLConnection createConnection(String toolsPath, int port) throws MalformedURLException, IOException {
        StringBuffer sb = new StringBuffer("/tools/installTool");
        addRequestParam(sb, "force", "true");
        addRequestParam(sb, "xmlmeta", toolsPath);
        URL url = new URL("http", "localhost", port, sb.toString());
        return (HttpURLConnection) url.openConnection();
    }

    private static void establishConnect(HttpURLConnection connection, int attemptCount) throws IOException {
        boolean hasError;
        do {
            hasError = false;
            try {
                if (firstTimeConnection) {
                    System.out.println("Trying to Connect to QueWeb server process...");
                    firstTimeConnection = false;
                }
                connection.connect();
            }
            catch(ConnectException e) {
                hasError = true;
                if (attemptCount--==0) {
                    System.out.println("Attempt count is over! Startup QueWeb server and try again!");
                    throw e;
                }
                else {
                    try {
                        Thread.sleep(1000);
                    }
                    catch(InterruptedException ie) {
                        ie.printStackTrace();
                    }
                }
            }
        } while(hasError && attemptCount>0);
    }

    private static void fillTools(HttpURLConnection connection, int attemptCount) throws IOException {
        establishConnect(connection, attemptCount);
        System.out.println("Connected to QueWeb Server successfully.");
        System.out.println("Running QueWeb Tools Installation scripts...");
        System.out.flush();
        int len = connection.getInputStream().available();
        if (len > 0) {
            InputStreamReader isr = new InputStreamReader(connection.getInputStream(), "Cp1251");
            //read from input stream
            int i = len;
            while ((isr.read() != -1) && (--i > 0)) {
            }
        }
        System.out.println("QueWeb Installation Tools finished execution successfully.");
    }

    public static void main(String[] args) {
        if (args.length < 2) {
            throw new IllegalArgumentException("Arguments [CoreXMLPath;AppXMLPath] [port] [attempCount] was not found");
        }
        try {
            System.out.println("Collecting and populating environment information for QueWeb tools...");
            fillTools(createConnection(args[0], Integer.parseInt(args[1])), Integer.parseInt(args[2]));
            System.out.println("Tools have been installed OK!");
        }
        catch (Exception e) {
            System.out.println("Tools have not been installed. Error is:");
            e.printStackTrace();
        }
    }

}
