/**
 * 文件名：ResourceTexture.java
 * 描述：ResourceTexture工具类
 * 包名：cn.com.kmlt.monstarBase.utils.texture
 * 作者：WENJQ
 * 创建日期：2016年05月26日
 * 
 */
package com.mgq.base.utils.texture;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.SparseArray;

import java.io.IOException;
import java.io.InputStream;

public final class ResourceTexture extends Texture {
    private static final SparseArray<ResourceTexture> cache = new SparseArray<ResourceTexture>();

    private final int mResourceId;
    private final boolean mScaled;

    public static ResourceTexture createResourceTexture(int resourceId) {
        return createResourceTexture(resourceId, true);
    }

    public static ResourceTexture createResourceTexture(int resourceId, boolean scaled) {
        ResourceTexture texture = cache.get(resourceId);
        if (texture == null && resourceId != 0) {
            texture = new ResourceTexture(resourceId, scaled);
            cache.put(resourceId, texture);
        }
        return texture;
    }

    private ResourceTexture(int resourceId, boolean scaled) {
        mResourceId = resourceId;
        mScaled = scaled;
    }

    @Override
    public Bitmap load(Context context) {
        if (mState == STATE_UNLOADED) {
            mState = STATE_LOADED;
            loadTextureAsync(context);
        }
        return mBitmap;
    }

    private void loadTextureAsync(Context context) {
        // Load a bitmap from the resource.
        Bitmap bitmap = null;
        if (mScaled) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            bitmap = BitmapFactory.decodeResource(context.getResources(), mResourceId, options);
        } else {
            InputStream inputStream = context.getResources().openRawResource(mResourceId);
            if (inputStream != null) {
                try {
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                    bitmap = BitmapFactory.decodeStream(inputStream, null, options);
                } catch (Exception e) {
                } finally {
                    try {
                        inputStream.close();
                    } catch (IOException e) { /* ignore */
                    }
                }
            }
        }

        mBitmap = bitmap;
    }
}
