package com.example.patrice.http01;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

// http://www.codexpedia.com/android/asynctask-and-httpurlconnection-sample-in-android/

// meteo super

// https://gist.github.com/udacityandroid/d6a7bb21904046a91695

public class http05 extends AppCompatActivity
{

    TextView txtResponse;
    Button btnSend;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.http05_layout);

        txtResponse = (TextView) findViewById(R.id.txtResponseId);
        btnSend     = (Button) findViewById(R.id.btnSendId);

    }

    public void btnOnClickHandler(View v)
    {
        btnSend.setEnabled(false);  // Disable the button
        new HttpTask().execute("https://www.android.com"); // Send HTTP request
        Toast.makeText(this, "Send", Toast.LENGTH_LONG).show(); // Toast a message
    }


    // Run the HTTP request in a background thread, separating from the main UI thread
    private class HttpTask extends AsyncTask<String, Void, String>
    {
        @Override
        protected String doInBackground(String... strURLs)
        {
            URL url = null;
            HttpURLConnection conn = null;
            try
            {
                url = new URL(strURLs[0]);
                conn = (HttpURLConnection) url.openConnection();
                // Get the HTTP response code (e.g., 200 for "OK", 404 for "Not found")
                // and pass a string description in result to onPostExecute(String result)
                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK)
                {  // 200
                    return "OK (" + responseCode + ")";
                } else {
                    return "Fail (" + responseCode + ")";
                }
            }
            catch (IOException e)
            {
                return "Unable to retrieve web page. URL may be invalid.";
            }
        }

        // Displays the result of the AsyncTask.
        // The String result is passed from doInBackground().
        @Override
        protected void onPostExecute(String result)
        {
            txtResponse.setText(result);  // put it on TextView
        }
    }

}