package dapr.com.client;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class DaprClientApplication {

	private final static String saveBodyTmpl="{\"content\": \"%s\"}";
	private final static String delSelBodyTmpl="{\"id\": \"%s\"}";
	private final static String updateBodyTmpl="{\"id\": \"%s\", \"content\": \"%s\"}";

    public static void main(String[] args) throws InterruptedException {

		Thread sendThread = new Thread(new Runnable() {
			public void run() {
				int i=16;
				//while(!Thread.interrupted()){
					try {
						Thread.sleep(10000);
						i++;
						String str = "第"+ i +"个意见~~~";
					// 增
						String body=String.format(saveBodyTmpl,str);
						save(body);
					// 改
					//	String body=String.format(updateBodyTmpl, String.valueOf(i), str);
					//	update(body);
					// 删，查
					//	String body=String.format(delSelBodyTmpl, String.valueOf(i));
					//  select(body);
					//  delete(body);

					} catch (Exception e) {
						e.printStackTrace();
					}
			//	}
			}
		});

		sendThread.start();
		Thread.sleep(5*60*60*1000);
    }

	/**
	 * 新增信息
	 * @param body
	 * @throws IOException
	 */
	private static void save(String body) throws IOException {
		sendRequest(body,"save");
	}

	private static void update(String body) throws IOException {
		sendRequest(body,"update");
	}

	private static void select(String body) throws IOException {
		sendRequest(body,"select");
	}

	private static void delete(String body) throws IOException {
		sendRequest(body,"delete");
	}

	/**
	 *
	 * @param body
	 * @param mothed
	 * @throws IOException
	 */
	private static void sendRequest(String body, String mothed) throws IOException {

		String httpPort = System.getenv("DAPR_HTTP_PORT");
		if (httpPort == null) {
			httpPort = "3500";
		}


		String resultUrl = "http://121.43.155.15:" + httpPort + "/v1.0/invoke/java-service/method/" + mothed;

		URL url = new URL(resultUrl);

		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("POST");
		connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
		connection.setRequestProperty("Connection", "Keep-Alive");
		connection.setUseCaches(false);
		connection.setDoOutput(true);
		connection.setDoInput(true);
		System.out.println("request body:"+body);
		DataOutputStream out = new DataOutputStream(connection.getOutputStream());
		out.write(body.getBytes("UTF-8"));
		out.flush();
		out.close();

		connection.connect();

		BufferedReader bReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

		String line, resultStr = "";

		while (null != (line = bReader.readLine())) {
			resultStr += line;
		}
		System.out.println(resultStr);
		bReader.close();
	}

}



