package de.winniepat.citrus.utils.texture;

import icyllis.modernui.graphics.*;
import icyllis.modernui.graphics.drawable.Drawable;
import net.minecraft.util.Identifier;
import org.jetbrains.annotations.NotNull;

import java.io.ByteArrayInputStream;

public class CdnTextureDrawable extends Drawable {

    private Identifier textureId;
    private Image mImage;
    private byte[] mImageData;

    public CdnTextureDrawable() {
        this.textureId = null;
        this.mImage = null;
        this.mImageData = null;
    }

    public CdnTextureDrawable(Identifier textureId) {
        this.textureId = textureId;
        this.mImage = null;
        this.mImageData = null;
    }

    public void setTextureId(Identifier textureId) {
        this.textureId = textureId;
        invalidateSelf();
    }

    public void setImageData(byte[] imageData) {
        this.mImageData = imageData;
        this.mImage = null;
        invalidateSelf();
    }

    private void createImageFromData() {
        if (mImageData == null || mImageData.length == 0) {
            return;
        }

        try {
            Bitmap bitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(mImageData));
            mImage = Image.createTextureFromBitmap(bitmap);
        } catch (Exception e) {
            mImage = null;
        }
    }

    public Identifier getTextureId() {
        return textureId;
    }

    public boolean hasTexture() {
        return textureId != null || mImage != null || mImageData != null;
    }

    @Override
    public void draw(@NotNull Canvas canvas) {
        if (mImage == null && mImageData != null) {
            createImageFromData();
        }

        if (mImage == null) {
            return;
        }

        Rect bounds = getBounds();
        if (bounds.isEmpty()) {
            return;
        }

        Paint paint = Paint.obtain();
        canvas.drawImage(mImage, null, bounds, paint);
        paint.recycle();
    }

    @Override
    public int getIntrinsicWidth() {
        return mImage != null ? mImage.getWidth() : -1;
    }

    @Override
    public int getIntrinsicHeight() {
        return mImage != null ? mImage.getHeight() : -1;
    }
}

