package com.yyrh.utils;

import android.content.Context;

import com.tencent.mmkv.MMKV;
import com.tencent.mmkv.MMKVHandler;
import com.tencent.mmkv.MMKVLogLevel;
import com.tencent.mmkv.MMKVRecoverStrategic;

import java.util.Locale;

/**
 * @author #Suyghur.
 * Created on 2021/10/15
 */
public class MMKVUtils implements MMKVHandler {

    public MMKV userKV = null;

    private MMKVUtils() {

    }

    public static MMKVUtils getInstance() {
        return MMKVUtilsHolder.INSTANCE;
    }

    public void init(Context context) {
        String dir = String.format(Locale.getDefault(), "%s/sdk_info", context.getExternalFilesDir("").getAbsolutePath());
        MMKV.initialize(context, dir, MMKVLogLevel.LevelInfo);
        MMKV.registerHandler(this);
        this.userKV = MMKV.mmkvWithID("user_info");
    }

    public void release() {
        MMKV.unregisterHandler();
    }

    @Override
    public MMKVRecoverStrategic onMMKVCRCCheckFail(String mmapID) {
        return MMKVRecoverStrategic.OnErrorDiscard;
    }

    @Override
    public MMKVRecoverStrategic onMMKVFileLengthError(String mmapID) {
        return MMKVRecoverStrategic.OnErrorDiscard;
    }

    @Override
    public boolean wantLogRedirecting() {
        return true;
    }

    @Override
    public void mmkvLog(MMKVLogLevel level, String file, int line, String function, String message) {
        String log = String.format(Locale.getDefault(), "<%s:%s::%s>%s", file, line, function, message);
        YYLog.d(log);
    }

    private static final class MMKVUtilsHolder {
        private static final MMKVUtils INSTANCE = new MMKVUtils();
    }
}
