package com.example.patrice.http01;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class AsyncResponse01 extends AppCompatActivity implements AsyncResponse
{

    //api.openweathermap.org/data/2.5/weather?q=London,uk

    // d6d2615ac831ca64635fe09bedb45135

    //http://api.openweathermap.org/data/2.5/weather?q=Poitiers,fr&appid=XXX

    String key_api = "&appid=d6d2615ac831ca64635fe09bedb45135";

    String base_url ="http://api.openweathermap.org/data/2.5/weather?q=";
    EditText etCity;

    AsyncResponse asR= AsyncResponse01.this;
  //  MyAsyncTask myAsyncTask=new MyAsyncTask(AsyncResponse01.this,  asR);

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

        etCity=(EditText)findViewById(R.id.etCity);
        Button btn=(Button)findViewById(R.id.button);

        btn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                String city = etCity.getText().toString();
                String finalUrl = base_url+city+key_api;
                Log.d("url",finalUrl);

                MyAsyncTask myAsyncTask=new MyAsyncTask(AsyncResponse01.this,  asR);

                myAsyncTask.execute(finalUrl);//to start the asynctask, you have to use execute and passing the url



                //if(mTask != null){
                //    mTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                //}

            }
        });
    }
    @Override
    public void processFinish(String result, String url)
    {

        Toast.makeText(AsyncResponse01.this,result, Toast.LENGTH_LONG).show();
    }
}


class MyAsyncTask extends AsyncTask<String,String,String>
{
    ProgressDialog pd;

    Context context;
    public AsyncResponse aR;


    public MyAsyncTask(Context context, AsyncResponse aR)
    {
        this.context = context;
        //context=MainActivity.this
        this.aR = aR;
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
        pd=new ProgressDialog(context);
        pd.setMessage("working...");
        pd.show();//to show the message

    }

    @Override
    protected String doInBackground(String... params)
    {
        String r=GET(params[0]);
        return r;
    }

    private String GET(String url)
    {
        InputStream inputStream = null;
        String result = "";
        try {

            // create HttpClient
            HttpClient httpclient = new DefaultHttpClient();

            // make GET request to the given URL
            HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

            // receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();

            // convert inputstream to string
            if(inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";

        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }

        return result;
    }

    private String convertInputStreamToString(InputStream inputStream) throws IOException
    {
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;
    }

    @Override
    protected void onPostExecute(String result)
    {
        aR.processFinish(result,"");
        pd.dismiss();
    }

    @Override
    protected void onProgressUpdate(String... values)
    {
        super.onProgressUpdate(values);
    }
}