package com.sheep.gamegroup.util;

import android.os.Environment;

import com.kfzs.duanduan.utils.NumberFormatUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Locale;

/**
 * Created by realicing on 2018/5/24.
 * realicing@sina.com
 */
public class ForeverCacheUtil {
    private static ForeverCacheUtil instance;
    //.开头隐藏文件和隐藏文件夹
    private static final String FILE_PATH = "data/cache/a54df5a4s5d";
    private ForeverCacheUtil(){
        File file = new File(getCacheFilePath());
        if(!file.exists()){
            try {
                if(file.getParentFile().mkdirs())
                    if(file.createNewFile()){
                        LogUtil.println("ForeverCacheUtil", "yes");
                    } else {
                        LogUtil.println("ForeverCacheUtil", "no");
                    }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static ForeverCacheUtil getInstance() {
        if (instance == null)
            instance = new ForeverCacheUtil();
        return instance;
    }


    private static String getFileName() {
        return "a5sdf41a6sdf1asd1fd52145s";
    }

    private static String getCacheFilePath() {
        boolean hasSDCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (hasSDCard) { // SD卡根目录
            return Environment.getExternalStorageDirectory().toString() + File.separator + FILE_PATH + File.separator + getFileName();
        } else {  // 系统下载缓存根目录
            return Environment.getDownloadCacheDirectory().toString() + File.separator + FILE_PATH + File.separator + getFileName();
        }
    }


    private String readLineByPosition(int position) {
        List<String> list = FileUtil.readLines(getCacheFilePath());
        return ListUtil.getItem(list, position);
    }

    /**
     * 文件第一行保存版本号
     */
    public int getVersionCode() {
        String msg = readLineByPosition(0);
        return NumberFormatUtils.parseInteger(msg, 0);
    }

    /**
     * 保存版本号
     *
     * @param cur_version_code
     */
    public void saveVersionCode(int cur_version_code) {
        String line = String.format(Locale.CHINA, "%d", cur_version_code);
        saveFile(line, 0);
    }

    private void saveFile(String line, int position) {
        List<String> list = FileUtil.readLines(getCacheFilePath());
        if (list == null)
            list = ListUtil.emptyList();
        while (list.size() <= position) {
            list.add("");
        }
        list.set(position, line);
        StringBuilder content = new StringBuilder();
        for (String item : list) {
            content.append(item);
            content.append("\n");
        }
        FileUtil.saveFile(getCacheFilePath(), content.toString());
    }
}
