package com.sheep.gamegroup.util.viewHelper;

import android.content.Context;

import com.sheep.gamegroup.util.DataUtil;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;

import okhttp3.Call;
import rx.functions.Action1;

/**
 * Created by realicing on 2018/11/13.
 * realicing@sina.com
 * 缓存图片工具类
 */
public class CacheImageUtil {
    //缓存并加载图片
    public static void cacheAndLoadImg(String link, final Action1<File> action1){
        String path = CacheImageUtil.getCacheImg(link);
        if(path == null){
            CacheImageUtil.cacheImg(link, action1);
        } else {
            action1.call(new File(path));
        }
    }

    //已经缓存图片
    public static String getCacheImg(String link) {
        String name = String.valueOf(link.hashCode());
        String fileName = name + ".png";
        File file = new File(getImgCacheDirPath(), fileName);
        if(file.exists() && DataUtil.getAsInt("sheep_png_" + name, STATE_NOE) == STATE_SUCCESS){
            return file.getAbsolutePath();
        }
        return null;
    }

    public static final int STATE_NOE = 0;//无状态
    public static final int STATE_DOWNLOAD = 1;//下载中
    public static final int STATE_ERROR = 2;//下载失败
    public static final int STATE_SUCCESS = 3;//下载成功

    //缓存图片
    public static void cacheImg(String link, final Action1<File> action1) {
        final String name = String.valueOf(link.hashCode());
        String fileName = name + ".png";
        if (DataUtil.getAsInt("sheep_png_" + name, STATE_NOE) == STATE_DOWNLOAD) {//这里不好处理
            return;
        }
        DataUtil.putAsInt("sheep_png_" + name, STATE_DOWNLOAD);
        OkHttpUtils.get().url(link).build().execute(new FileCallBack(getImgCacheDirPath(), fileName) {
            @Override
            public void onError(Call call, Exception e, int id) {
                DataUtil.putAsInt("sheep_png_" + name, STATE_ERROR);
                if (action1 != null) {
                    action1.call(null);
                }
            }

            @Override
            public void onResponse(File response, int id) {
                if (response.exists()) {
                    DataUtil.putAsInt("sheep_png_" + name, STATE_SUCCESS);
                    if (action1 != null) {
                        action1.call(response);
                    }
                }
            }
        });
    }

    public static File getImgCacheDir() {
        return SheepApp.getInstance().getDir("img", Context.MODE_PRIVATE);
    }

    public static String getImgCacheDirPath() {
        return SheepApp.getInstance().getDir("img", Context.MODE_PRIVATE).getPath();
    }
}
