package com.sheep.gamegroup.util;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.widget.TextView;

import com.bumptech.glide.request.target.FixedSizeDrawable;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.ClassFileHelper;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;

import okhttp3.Call;

/**
 * Created by realicing on 2018/11/7.
 * realicing@sina.com
 */
public class UrlImageGetter implements Html.ImageGetter {

    private URLDrawable urlDrawable = null;
    private TextView textView;
    private int textSize;

    public UrlImageGetter(TextView textView) {
        this.textView = textView;
        textSize = (int) textView.getTextSize() * 2;
    }

    @Override
    public Drawable getDrawable(final String source) {
        Resources resources = SheepApp.getInstance().getResources();

        String fileName = source + ".png";
        File file = new File(ClassFileHelper.DIR, fileName);
        if (file.exists()) {
            urlDrawable = new URLDrawable(resources, BitmapFactory.decodeFile(file.getAbsolutePath()));
            urlDrawable.setBounds(0, 0, textSize, textSize);
            return urlDrawable;
        }
        urlDrawable = new URLDrawable(resources, BitmapFactory.decodeResource(resources, R.drawable.loading_01, null));
        urlDrawable.setBounds(0, 0, textSize, textSize);

        OkHttpUtils.get().url(ViewUtil.getNetImgByName(source)).build().execute(new FileCallBack(ClassFileHelper.DIR, fileName) {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(File response, int id) {
                if (response.exists()) {
                    urlDrawable.bitmap = BitmapFactory.decodeFile(response.getAbsolutePath());
                    urlDrawable.setBounds(0, 0, textSize, textSize);
                    textView.invalidate();
                    textView.setText(textView.getText());//不加这句显示不出来图片，原因不详
                }
            }
        });
        return urlDrawable;
    }

    public class URLDrawable extends BitmapDrawable {
        URLDrawable(Resources res, Bitmap bitmap) {
            super(res, bitmap);
        }

        public Bitmap bitmap;

        @Override
        public void draw(Canvas canvas) {
            if (bitmap != null) {
                canvas.drawBitmap(bitmap, 0, 0, getPaint());
            } else {
                super.draw(canvas);
            }
        }
    }
}