/*
 *  Copyright 2016 Jason Wee
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package co.weetech.jwms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.logging.Logger;

public class Jwms {
	
	private static Logger logger = null; 
	
	private static String USER_AGENT = "jwms-lib";
	private String urlString;
	private String crumb;
	private String username;
	private String password;
	
	public Jwms(String url, String crumb, String username, String password, Logger logger) {
		this.urlString = url;
		this.crumb = crumb;
		this.username = username;
		this.password = password;
	}
	
	public boolean send(String message, String result, String duration, String displayName, String description) 
			throws IOException {
		
		URL url = new URL(urlString);
		HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
		
		String userpass = username + ":" + password;
		String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
		
		// all the request header required.
		httpCon.setRequestMethod("POST");
		httpCon.setRequestProperty("User-Agent", USER_AGENT);
		httpCon.setRequestProperty(".crumb", crumb);
		httpCon.setRequestProperty("Authorization", basicAuth);
		httpCon.setDoOutput(true);
		
		String jenkinsString= "<run><log encoding=\"hexBinary\">%s</log><result>%s</result><duration>%s</duration>"
				+ "<displayName>%s</displayName><description>%s</description></run>";
		byte[] outputBytes = String.format(jenkinsString, message, result, duration, displayName, description).getBytes();
		OutputStream os = httpCon.getOutputStream();
		os.write(outputBytes);
		os.flush();
		os.close();

		int responseCode= httpCon.getResponseCode();
		if (getLogger() != null) {
			getLogger().info(String.format("url '%s' response code '%s'", urlString, responseCode));
		}
		
		if (responseCode == HttpURLConnection.HTTP_OK) {
			BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
			String inputLine;
			StringBuilder response = new StringBuilder();
			
			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			
			in.close();
			
			if (getLogger() != null) {
				getLogger().info(String.format("response '%s'", response.toString()));
			}
			return true;
		} else {
			return false;
		}
	}
	
	public static Logger getLogger() {
		return logger;
	}

	public static void setLogger(Logger logger) {
		Jwms.logger = logger;
	}
	
	public static void main(String[] args) throws IOException {
		// jenkins url string
		String urlString = "";
		
		// jenkins crumb 
		String crumb = "";
		
		// jenkins username
		String username = "";
		
		// jenkins api associated with the user
		String password = "";
		
		// the message in hex
		String message = "444f4e450a";
		
		// the result in numeric, 0 is success , others fail
		String result = "0";
		
		// duration in milli seconds
		String duration = "2000";
		
		// the name to display in jenkins for this run
		String displayName = "local test";
		
		// the more elaborative description for this run
		String description="";
		
		// how to actually initalize and send it.
		Jwms agent = new Jwms(urlString, crumb, username, password, null);
		agent.send(message, result, duration, displayName, description);
		
		// TODO
		// move the above to test code
		// we need string to hex method
		// we need duration second auto convert to milliseconds
		// we need rpm spec
	}



}

@@ -857,16 +857,52 @@
 ogger;%0A%0A
+import co.weetech.util.StringUtil;%0A%0A
 public c
@@ -2195,23 +2195,41 @@
 String, 
+StringUtil.toHex(
 message
+)
 , result
@@ -3178,1000 +3178,8 @@
 %0A%09%7D%0A
+
 %09%0A
-%09public static void main(String%5B%5D args) throws IOException %7B%0A%09%09// jenkins url string%0A%09%09String urlString = %22%22;%0A%09%09%0A%09%09// jenkins crumb %0A%09%09String crumb = %22%22;%0A%09%09%0A%09%09// jenkins username%0A%09%09String username = %22%22;%0A%09%09%0A%09%09// jenkins api associated with the user%0A%09%09String password = %22%22;%0A%09%09%0A%09%09// the message in hex%0A%09%09String message = %22444f4e450a%22;%0A%09%09%0A%09%09// the result in numeric, 0 is success , others fail%0A%09%09String result = %220%22;%0A%09%09%0A%09%09// duration in milli seconds%0A%09%09String duration = %222000%22;%0A%09%09%0A%09%09// the name to display in jenkins for this run%0A%09%09String displayName = %22local test%22;%0A%09%09%0A%09%09// the more elaborative description for this run%0A%09%09String description=%22%22;%0A%09%09%0A%09%09// how to actually initalize and send it.%0A%09%09Jwms agent = new Jwms(urlString, crumb, username, password, null);%0A%09%09agent.send(message, result, duration, displayName, description);%0A%09%09%0A%09%09// TODO%0A%09%09// move the above to test code%0A%09%09// we need string to hex method%0A%09%09// we need duration second auto convert to milliseconds%0A%09%09// we need rpm spec%0A%09%7D%0A%0A%0A%0A
 %7D%0A

convert string message into hex