package com.gh.gamecenter.common.retrofit;

import android.content.Context;

import com.gh.gamecenter.common.utils.FileUtils;
import com.gh.gamecenter.common.utils.TimestampUtils;
import com.gh.gamecenter.core.utils.MD5Utils;

import java.io.File;
import java.io.IOException;

/**
 * Created by LGT on 2016/12/5.
 * OkHttp 缓存工具
 */
public class OkHttpCache {

    private static String cachePath;

    // 根据url获取缓存数据
    public static byte[] getCache(Context context, String url) {
        if (getCachePath(context) == null || url == null) {
            return null;
        }
        String key = MD5Utils.getUrlMD5(url) + ".1";
        File cacheFile = new File(getCachePath(context));
        if (cacheFile.isDirectory()) {
            for (File file : cacheFile.listFiles()) {
                if (file.getName().equals(key)) {
                    return FileUtils.readFile(file);
                }
            }
        }
        return null;
    }

    public static String getCachePath(Context context) {
        if (cachePath == null) {
            File cacheFile = new File(context.getCacheDir(), "okhttp");
            cachePath = cacheFile.getAbsolutePath();
        }
        return cachePath;
    }

    // 根据url保存对应的okhttp的缓存
    public static void putCache(Context context, String url, byte[] data) {
        if (getCachePath(context) == null || url == null || data == null) {
            return;
        }
        String key = MD5Utils.getUrlMD5(url) + ".1";
        FileUtils.saveFile(new File(getCachePath(context), key), data);
    }

    // 根据url修改对应的okhttp的缓存
    public static void updateCache(Context context, String url, byte[] data) {
        if (getCachePath(context) == null || url == null || data == null) {
            return;
        }
        try {
            String key = MD5Utils.getUrlMD5(url) + ".1";
            File file = new File(getCachePath(context), key);
            if (file.exists()) {
                file.createNewFile();
            }
            FileUtils.saveFile(file, data);
            // 如果url包含timestamp，去除timestamp更新缓存
            if (url.contains("timestamp")) {
                url = TimestampUtils.removeTimestamp(url);
                updateCache(context, url, data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
