package eu.dnetlib.data.statsmanager;


import org.apache.log4j.Logger;
import org.apache.tools.ant.util.Base64Converter;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;


public class CacheController {

    private HashMap<String, URL> actions;

    private Logger log = Logger.getLogger(this.getClass());

    private String httpsCredentials;

    public CacheController() {
    }

    public void executeCommand(String action, Map<String, String> parameters) throws Exception {


        /*if (cacheURL != null && !cacheURL.isEmpty()) {
            log.debug("existing cache url " + this.getActions().get(action));
            String actionUrl = this.getActions().get(action).toString();
            actionUrl = actionUrl.substring(actionUrl.lastIndexOf("/"), actionUrl.length());
            url = new URL(cacheURL + actionUrl);
            log.info("creds for url " + url + "  " + credentials);
            executeRemoteScript(url, credentials);

        } else {
          */

        String urlString = this.actions.get(action).toString();
        for (Map.Entry<String, String> e : parameters.entrySet()) {
            if (!e.getKey().equals("cache")&&!e.getKey().equals("error")) {
                urlString += "&" + e.getKey() + "=" + e.getValue();


            }
        }
        // credentials = this.cacheCredInfo.get(url.toString().substring(0, url.toString().lastIndexOf("/")));
        executeRemoteScript(new URL(urlString));
    }

    private void executeRemoteScript(URL url) throws Exception {
        try {


            Base64Converter converter = new Base64Converter();
            BufferedReader in = null;

            if (url.toString().startsWith("https://")) {

                String encoding = converter.encode(httpsCredentials.getBytes("UTF-8"));

                log.debug("Using https : " + url.toString());
                HttpsURLConnection yc = (HttpsURLConnection) url.openConnection();
                yc.setRequestProperty("Authorization", String.format("Basic %s", encoding));
                in = new BufferedReader(
                        new InputStreamReader(
                                yc.getInputStream()));
            } else {
                  log.debug("Using normal url : " + url.toString());
                URLConnection yc = (URLConnection) url.openConnection();

                in
                        = new BufferedReader(
                        new InputStreamReader(
                                yc.getInputStream()));

            }

            String inputLine;

            while ((inputLine = in.readLine()) != null)
                log.debug(inputLine);


            in.close();


        } catch (Exception e) {
            log.error("Error while calling php script over http. Reason: " + e);
            throw new Exception(e);
        }
    }

    public HashMap<String, URL> getActions() {
        return actions;
    }

    public void setActions(HashMap<String, URL> actions) {
        this.actions = actions;
    }

    public CacheController(HashMap<String, URL> actions) {
        this.actions = actions;
    }


    public String getHttpsCredentials() {
        return httpsCredentials;
    }

    public void setHttpsCredentials(String httpsCredentials) {
        this.httpsCredentials = httpsCredentials;
    }
}
