

package com.anpmech.launcher;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.widget.ImageView;
import com.anpmech.launcher.threading.SimpleTaskConsumerManager;


public final class ImageLoadingTask implements Runnable, SimpleTaskConsumerManager.Task {

    private final Context mContext;

    private final int mIconSizePixels;

    private final ImageView mImageView;

    private final LaunchableActivity mLaunchableActivity;

    private Drawable mActivityIcon;

    private ImageLoadingTask(final ImageView imageView, final LaunchableActivity launchableActivity,
            final int iconSizePixels) {
        mContext = imageView.getContext();
        mImageView = imageView;
        mLaunchableActivity = launchableActivity;
        mIconSizePixels = iconSizePixels;
    }

    @Override
    public boolean doTask() {
        mActivityIcon = mLaunchableActivity.getActivityIcon(mContext, mIconSizePixels);
        final Handler handler = new Handler(mContext.getMainLooper());

        handler.post(this);

        return true;
    }

    @Override
    public void run() {
        if (mImageView.getTag() == mLaunchableActivity) {
            mImageView.setImageDrawable(mActivityIcon);
        }
    }

    public static class Factory {

        private final int mIconSizePixels;

        public Factory(final int iconSizePixels) {
            mIconSizePixels = iconSizePixels;
        }

        public SimpleTaskConsumerManager.Task create(final ImageView imageView,
                final LaunchableActivity activity) {
            return new ImageLoadingTask(imageView, activity, mIconSizePixels);
        }
    }

}
