package cgmblelib.utils;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;

import cgmblelib.base.BSharedPreferences;
import cgmblelib.qr.QRInformation;

public class SharedPreferencesLibraryUtil {

    BSharedPreferences prefsHelper;
    private final String QRInfo = "QRInformation";
    private final String SyncMeta = "SyncMeta";
    private final String PatientId = "PatientId";


    public SharedPreferencesLibraryUtil(Context context) {
        prefsHelper = BSharedPreferences.getInstance(context);
    }

    public QRInformation getQRInformation() {
        try {
            String message = prefsHelper.getData(QRInfo);
            if (message == null || message.isEmpty()) {
                return null;
            }
            return new Gson().fromJson(message, QRInformation.class);
        } catch (Exception e) {
            Log.d("Error => ", "getQRInformation: " + e.getMessage());
            return null;
        }
    }


    public void setQRInformation(String transmitterName, String qrmessage, float K, float R, String sensor) {
        try {
            Log.d("Error => ", "setQRInformation: " + transmitterName + qrmessage + K + R + sensor);
            prefsHelper.saveData(QRInfo, new Gson().toJson(new QRInformation(transmitterName, qrmessage, R, K, sensor)));
        } catch (Exception e) {
            Log.d("Error => ", "setQRInformation: " + e.getMessage());
        }
    }

    public void setLastSyncData(SyncMeta syncMeta) {
        try {
            prefsHelper.saveData(SyncMeta, new Gson().toJson(syncMeta));
        } catch (Exception e) {
            Log.d("Error => ", "setLastSyncData: " + e.getMessage());
        }
    }

    public SyncMeta getLastSyncData() {
        try {
            String message = prefsHelper.getData(SyncMeta);
            if (message == null || message.isEmpty()) {
                return null;
            }
            return new Gson().fromJson(message, SyncMeta.class);
        } catch (Exception e) {
            Log.d("Error => ", "getLastSyncData: " + e.getMessage());
            return null;
        }
    }

    public void setLastPatientId(String patientId) {
        try {
            prefsHelper.saveData(PatientId, patientId);
        } catch (Exception e) {
            Log.d("Error => ", "setLastUserId: " + e.getMessage());
        }
    }

    public String getLastPatientId() {
        try {
            String message = prefsHelper.getData(PatientId);
            if (message == null || message.isEmpty()) {
                return null;
            }
            return message;
        } catch (Exception e) {
            Log.d("Error => ", "getLastUserId: " + e.getMessage());
            return null;
        }
    }

    public void clearQRInformation() {
        prefsHelper.saveData(QRInfo, null);
    }
}
