package org.bdware.sc.http;

import org.bdware.sc.util.JsonUtil;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Scanner;

public class ApiGate {
    private final Get get;

    public ApiGate(String ipAddress, int port) {
        this.get = new HttpGet(ipAddress, port);
    }

    public ApiGate(String ipAddress) {
        this.get = new HttpGet(ipAddress, 6161);
    }

    public String get(String pkgName, String method, String arg) {
        return get.get(pkgName, method, arg);
    }

    private interface Get {
        String get(String pkgName, String methodName, String arg);
    }

    static class Args {
        String pkgName;
        String method;
        String arg;
    }

    private static class HttpGet implements Get {
        String url;

        public HttpGet(String ip, int port) {
            url = "http://" + ip + ":" + port + "/CMDManager?getMessage=";
        }

        public String get(String pkgName, String name, String arg) {
            Args args = new Args();
            args.pkgName = pkgName;
            args.method = name;
            args.arg = arg;
            return sendHttpGet(url + URLEncoder.encode(JsonUtil.toJson(args)));
        }

        private String sendHttpGet(String str) {
            try {
                System.out.println("[APIGate] sendHttp:" + str);
                URL url = new URL((str));
                URLConnection connection = url.openConnection();
                connection.setReadTimeout(10 * 1000);
                InputStream input = connection.getInputStream();
                Scanner sc = new Scanner(input);
                StringBuilder sb = new StringBuilder();
                while (sc.hasNextLine()) {
                    sb.append(sc.nextLine()).append("\n");
                }
                sc.close();
                return sb.toString();
            } catch (Exception e) {
                ByteArrayOutputStream bo = new ByteArrayOutputStream();
                e.printStackTrace(new PrintStream(bo));
                return bo.toString();
            }
        }
    }
}
