package com.eni.android.asynctask;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.eni.android.asynctask.R;

public class AsyncTaskActivity extends Activity {

	private Button launchAsync;
	private ProgressBar progress;
	private myDownloadTask downloadTask;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.async_task);
		
		final String uri = "";
		
		launchAsync = (Button) findViewById(R.id.launch_async);
		launchAsync.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				downloadTask = new myDownloadTask();
				downloadTask.execute(uri);
			}
		});
		progress = (ProgressBar) findViewById(R.id.progress);
	}
	
    public class myDownloadTask extends AsyncTask<String, Integer, String> {
    	@Override
    	protected void onPreExecute() {
    		super.onPreExecute();
    		launchAsync.setVisibility(View.GONE);
    		progress.setVisibility(View.VISIBLE);
    	}
    	
    	@Override
    	protected String doInBackground(String... params) {
    		@SuppressWarnings("unused")
			String uri = params[0];
    		String result = "";
    		for (int i = 1; i <= 10; ++i) {
    			try {
					Thread.sleep(1000L);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
    			publishProgress(i * 10);
    			result += i;
    		}
    		return result;
    	}
    	
    	@Override
    	protected void onProgressUpdate(Integer... progress) {
    		super.onProgressUpdate(progress);
    		AsyncTaskActivity.this.progress.setProgress(progress[0]);
    	}
    	
    	@Override
    	protected void onPostExecute(String result) {
    		super.onPostExecute(result);
    		Toast.makeText(AsyncTaskActivity.this, R.string.fin_de_l_ex_cution_du_traitement_en_arri_re_plan, Toast.LENGTH_LONG).show();
    		launchAsync.setVisibility(View.VISIBLE);
    		progress.setVisibility(View.GONE);
    	}
    }

}
