package com.appideas.base;

import android.app.ProgressDialog;
import android.os.AsyncTask;

/*
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
*/

/**
 * The APPideas Remote Requests.<br/>
 *
 * @author		costmo
 * @version		20111220
 * @since		20111220
 */
public class AiRRs extends AsyncTask<String, Void, String>
{
	//private static final HttpClient httpClient;

	/**
	 * The URI of the request
	 */
	public String mUri;

	/**
	 * Array of field names to post
	 */
	public String[] mPostFields;

	/**
	 * Array of data to post
	 */
	public String[] mPostData;

	/**
	 * Server response
	 */
	public String mResponse;

	/**
	 * A progress dialog
	 */
	public ProgressDialog mWaitDialog;

	/**
	 * Request timeout value
	 */
	public int mConnectionTimeout;

	/**
	 * Debug tag
	 */
	public static String mTag = "AiRRs";

	/**
	 * Blank class constructor
	 *
	 * @since		20111220
	 */
	public AiRRs()
	{
		this.mPostFields = new String[0];
		this.mPostData = new String[0];
		this.mResponse = "";
		this.mConnectionTimeout = 3000;
	}

	/**
	 * Class constructor to populated inputs
	 *
	 * @since		20111220
	 * @param		postFields			Array of field names to post
	 * @param		postData			Array of data to post
	 */
	public AiRRs( String[] postFields, String[] postData )
	{
		this.mPostFields = postFields;
		this.mPostData = postData;
		this.mResponse = "";
		this.mConnectionTimeout = 3000;
	}


	@Override
	protected String doInBackground( String... params )
	{
		String returnValue = "";

		/*HttpParams httpParameters = new BasicHttpParams();

		// Set the timeout in milliseconds until a connection is established.
		int timeoutConnection = this.mConnectionTimeout;
		HttpConnectionParams.setConnectionTimeout( httpParameters, timeoutConnection );
		int timeoutSocket = 100000;
		HttpConnectionParams.setSoTimeout( httpParameters, timeoutSocket );
		HttpClient httpclient = new DefaultHttpClient( httpParameters );

		HttpPost httppost = new HttpPost( params[0] );



		this.mResponse = returnValue;

		return returnValue;*/

		//// TODO: 8/23/16 finish converting away from apache commons if using again

		/*
		try
		{
			Map<String,String> nameValuePairs = new HashMap<>();
			for( int i = 0; i < this.mPostFields.length; i++ )
			{
				try
				{
					nameValuePairs.put( this.mPostFields[i], this.mPostData[i] );
				}
				catch( ArrayIndexOutOfBoundsException e )
				{
					//  there were more data elements than fields
				}
			}

			httppost.setEntity( new UrlEncodedFormEntity( nameValuePairs ) );

			// Execute HTTP Post Request
			HttpResponse response = httpclient.execute( httppost );
			returnValue = EntityUtils.toString( response.getEntity() );
		}
		catch( ClientProtocolException e )
		{
			returnValue = "Could not connect to remote host. " + e.toString();
		}
		catch( IOException e )
		{
			returnValue = "Could not connect to remote host. " + e.toString();
		}

		//Server Communication part - it's relatively long but uses standard methods

		//Encoded String - we will have to encode string by our custom method (Very easy)
		String encodedStr = AiSTr.getEncodedData(dataToSend);

		//Will be used if we want to read some data from server
		BufferedReader reader = null;

		//Connection Handling
		try {
			//Converting address String to URL
			URL url = new URL(SERVER_ADDRESS + "Register.php");
			//Opening the connection (Not setting or using CONNECTION_TIMEOUT)
			HttpURLConnection con = (HttpURLConnection) url.openConnection();

			//Post Method
			con.setRequestMethod("POST");
			//To enable inputting values using POST method
			//(Basically, after this we can write the dataToSend to the body of POST method)
			con.setDoOutput(true);
			OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
			//Writing dataToSend to outputstreamwriter
			writer.write(encodedStr);
			//Sending the data to the server - This much is enough to send data to server
			//But to read the response of the server, you will have to implement the procedure below
			writer.flush();

			//Data Read Procedure - Basically reading the data comming line by line
			StringBuilder sb = new StringBuilder();
			reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

			String line;
			while((line = reader.readLine()) != null) { //Read till there is something available
				sb.append(line + "\n");     //Reading and saving line by line - not all at once
			}
			line = sb.toString();           //Saving complete data received in string, you can do it differently

			//Just check to the values received in Logcat
			Log.i("custom_check","The values received in the store part are as follows:");
			Log.i("custom_check",line);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(reader != null) {
				try {
					reader.close();     //Closing the
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		//Same return null, but if you want to return the read string (stored in line)
		//then change the parameters of AsyncTask and return that type, by converting
		//the string - to say JSON or user in your case*/
		return null;
	}

	@Override
	protected void onPreExecute()
	{

	}


}