package fwauth;
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 org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.google.gson.Gson;

public class HttpCallURL {

	private static final String USER_AGENT = "Mozilla/5.0";


	//private static final String POST_URL = "http://demo.tarka.in/floating_walls/app.php?";
	private static final String POST_URL = "http://aws.tarka.in/floating_walls/app.php?";

	private static  String POST_PARAMS = "a=validateUsernameAndPasswordAndMAC";

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

		
		sendPOST("Tarka","msr_1234","1212");
		System.out.println("POST DONE");
	}

	

	public static JSONObject sendPOST(String userName,String password,String macId) throws IOException {
		
		String errorCode="";
		POST_PARAMS+="&usr="+userName+"&password="+password+"&mac_id="+macId+"";
		
		URL obj = new URL(POST_URL);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();
		con.setRequestMethod("POST");
		con.setRequestProperty("User-Agent", USER_AGENT);

		// For POST only - START
		con.setDoOutput(true);
		OutputStream os = con.getOutputStream();
		os.write(POST_PARAMS.getBytes());
		os.flush();
		os.close();
		// For POST only - END

		int responseCode = con.getResponseCode();
		System.out.println("POST Response Code :: " + responseCode);
		
		JSONObject returnObj=new JSONObject();
		returnObj.put("errorCode", "");
		returnObj.put("jar_session_id", "");

		if (responseCode == HttpURLConnection.HTTP_OK) { //success
			BufferedReader in = new BufferedReader(new InputStreamReader(
					con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();

			// print result
			System.out.println(response.toString());
			JSONParser parser = new JSONParser();
			try {
				JSONObject json = (JSONObject) parser.parse(response.toString());
				 errorCode=json.get("error_code").toString();
					if(errorCode.equals("0"))
					{
						JSONObject dataObj=(JSONObject)json.get("data");
						String jar_session_id=dataObj.get("jar_session_id").toString();
						returnObj.put("jar_session_id", jar_session_id);
					}
					returnObj.put("errorCode", errorCode);
					returnObj.put("msg",json.get("data").toString());
				
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			System.out.println("POST request not worked");
		}
		
		return returnObj;
	}

}