package io.hbar.cordova.util;

import android.util.Log;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.PluginResult;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;

import org.apache.http.entity.StringEntity;
import org.apache.http.entity.ContentType;


public class HTTPProxy extends CordovaPlugin {

	public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {

		if (action.equals("get")) {

			try {
				String url = args.getString(0);
		
				HttpClient client = HttpClientBuilder.create().build();
				HttpGet request = new HttpGet(url);
		
				if(args.length() > 1) {
					String auth = args.getString(1);
					request.addHeader("Authorization", "Basic " + auth);
				}

				HttpResponse response = client.execute(request);

				if(response.getStatusLine().getStatusCode() / 100 == 2) {
		
					BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			
					StringBuffer result = new StringBuffer();
					String line = "";
					while ((line = rd.readLine()) != null) {
						result.append(line);
					}

					callbackContext.success(result.toString());
				
				} else {
					callbackContext.error(response.getStatusLine().getStatusCode() + ": " + response.getStatusLine().getReasonPhrase());
				}

			} catch(Exception e) {
				callbackContext.error("ERROR");
			}
			
			return true;
		}


		if (action.equals("post")) {

			try {
				String url = args.getString(0);
				String auth = args.getString(1);
				String payload = args.getString(2);
		
				HttpClient client = HttpClientBuilder.create().build();
				HttpPost request = new HttpPost(url); 
		
				request.addHeader("Authorization", "Basic " + auth);

				request.setEntity(new StringEntity(payload));


				HttpResponse response = client.execute(request);

				if(response.getStatusLine().getStatusCode() / 100 == 2) {
		
					BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			
					StringBuffer result = new StringBuffer();
					String line = "";
					while ((line = rd.readLine()) != null) {
						result.append(line);
					}

					callbackContext.success(result.toString());

				} else {
					callbackContext.error(response.getStatusLine().getStatusCode() + ": " + response.getStatusLine().getReasonPhrase());
				}

			} catch(Exception e) {
				callbackContext.error("ERROR");
			}
			
			return true;
		}


		return false;
	}

}
