package course.examples.ThreadingHandlerRunnableReuseTask;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.widget.ImageView;
import android.widget.ProgressBar;


public class LoadIconTask implements Runnable {
    
    private Handler handler;
    private IconLoader activity;
    private int resId;
    private int mDelay;
    private Bitmap mBitmap;

    public interface IconLoader {
        public ProgressBar getProgressBar();
        public ImageView getImageView();
    }

    //Constructor. Pasamos eh Handler y el contexto (activity en la que se ejecuta)
    public LoadIconTask(Context context) {
        this.handler = new Handler();
        this.activity = (IconLoader) context;
        this.mDelay = 500;

        try {
            this.activity = (IconLoader) activity;
        }
        catch (ClassCastException e) {
            throw new ClassCastException(this.activity.toString() + " debe Implementar IconLoader");
        }

    }

    public void setResId(int resId) {
        this.resId = resId;
    }

    @Override
    public void run() {

        handler.post(new Runnable() {
            @Override
            public void run() {
                activity.getProgressBar().setVisibility(ProgressBar.VISIBLE);
            }
        });

        mBitmap = BitmapFactory.decodeResource(((Context) activity).getResources(), resId);

        // Simulating long-running operation

        for (int i = 1; i < 11; i++) {
            sleep();
            final int step = i;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    activity.getProgressBar().setProgress(step * 10);
                }
            });
        }

        handler.post(new Runnable() {
            @Override
            public void run() {
                activity.getImageView().setImageBitmap(mBitmap);
            }
        });

        handler.post(new Runnable() {
            @Override
            public void run() {
                activity.getProgressBar().setVisibility(ProgressBar.INVISIBLE);
            }
        });
    }        

    private void sleep() {
        try {
            Thread.sleep(mDelay);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
