import {Alert} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
// https://react-native-async-storage.github.io/async-storage/docs/usage
// https://blog.csdn.net/AnitaSun/article/details/115204134

const set = async (key, value, obj = null) => {

    try {
        if (obj) {
            value = JSON.stringify(value);
        }
        await AsyncStorage.setItem(key, value);
    } catch (e) {
        // saving error
        console.log('设置内部存储失败', e);
        Alert.alert('设置内部存储失败');
    }
};

const get = async (key, obj = null) => {
    try {
        const value = await AsyncStorage.getItem(key);
        if (obj) {
            return value != null ? JSON.parse(value) : null;
        }
        return value;
    } catch (e) {
        // error reading value
        console.log('获取内部存储失败', e);
        Alert.alert('获取内部存储失败');
    }
};

const remove = async (key) => {
    try {
        await AsyncStorage.removeItem(key);
    } catch (e) {
        // remove error
        console.log('删除内部存储失败', e);
        Alert.alert('删除内部存储失败');
    }
};

const clear = async (key) => {
    try {
        await AsyncStorage.clear();
    } catch (e) {
        // remove error
        console.log('清空内部存储失败', e);
        Alert.alert('清空内部存储失败');
    }
};


export default {
    clear,
    remove,
    get,
    set,
};
