package org.ntlab.radishforandroidstudio.framework.RWT;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;

import org.ntlab.radishforandroidstudio.framework.model3D.Position3D;
import org.ntlab.radishforandroidstudio.java3d.ImageComponent2D;
import org.ntlab.radishforandroidstudio.java3d.Texture;
import org.ntlab.radishforandroidstudio.java3d.Texture2D;

import java.io.InputStream;

/**
 * 画像ローダー
 * java3d.TextureLoaderから取ってきた
 * 物体に貼り付けるテクスチャとかには使えないと思われる
 * RWTSprite用
 *
 * @author s.iwatani
 */
public class RWTImageLoader {
    public static final int BY_REFERENCE = 2;
    public static final int Y_UP = 4;
    private InputStream in = null;
    private Resources res = null;
    private int id = 0;
    private Bitmap bitmap;
    private int format, texFormat;
    private Position3D size = null;

    public RWTImageLoader(InputStream in, int flags) {
        this.in = in;
    }

    public RWTImageLoader(Resources res, int id, int flags) {
        this(res, id, flags, ImageComponent2D.FORMAT_RGB);
    }

    /**
     * TextureLoaderコンストラクタ
     *
     * @author s.iwatani
     * @param res Resources
     * @param id リソースID
     * @param flags 知らん
     * @param format 画像がRGBかRGBAか ImageComponent2D.FORMAT_RGBまたはImageComponent2D.FORMAT_RGBA
     */
    public RWTImageLoader(Resources res, int id, int flags, int format) {
        this.res = res;
        this.id = id;
        setFormat(format);
    }

    /**
     * 画像がRGBかRGBAかをセット
     *
     * @param format ImageComponent2D.FORMAT_RGBまたはImageComponent2D.FORMAT_RGBA
     */
    public void setFormat(int format) {
        this.format = format;
        if (this.format == ImageComponent2D.FORMAT_RGB) {
            texFormat = Texture.RGB;
        }
        else {
            texFormat = Texture.RGBA;
        }
    }

    public ImageComponent2D getImage() {
        if (in != null) {
            bitmap = BitmapFactory.decodeStream(in);
        } else if (res != null) {
            bitmap = BitmapFactory.decodeResource(res, id);
        }
        if (format == ImageComponent2D.FORMAT_RGBA) {
            bitmap.setHasAlpha(true);
        }

        size = new Position3D(bitmap.getWidth(), bitmap.getHeight(), 0.0);
        return new ImageComponent2D(format, bitmap);
    }

    public Position3D getSize() {
        return size;
    }

    public ImageComponent2D setImage(Bitmap bitmap) {
        this.bitmap = bitmap;
        return new ImageComponent2D(format, this.bitmap);
    }

    public Texture getTexture() {
        ImageComponent2D ic2 = getImage();
        Texture tex = new Texture2D(Texture.BASE_LEVEL, texFormat, bitmap.getWidth(), bitmap.getHeight());
        tex.setImage(0, ic2);
        return tex;
    }
}
