package com.retrytech.strangerapp.utils;

import static android.content.Context.MODE_PRIVATE;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.retrytech.strangerapp.modal.User;
import com.retrytech.strangerapp.modal.fakeuser.FakeUser;
import com.retrytech.strangerapp.modal.settings.AppSettings;
import com.retrytech.strangerapp.retrofit.Const;

public class SessionManager {
    private SharedPreferences pref;
    private SharedPreferences.Editor editor;

    @SuppressLint("CommitPrefEdits")
    public SessionManager(Context context) {
        this.pref = context.getSharedPreferences(Const.PREF_NAME, MODE_PRIVATE);
        this.editor = this.pref.edit();
    }

    public void saveStringValue(String key, String value) {
        editor.putString(key, value);
        editor.apply();
    }

    public String getStringValue(String key) {
        return pref.getString(key, "");
    }

    public void saveBooleanValue(String key, boolean value) {
        editor.putBoolean(key, value);
        editor.apply();
    }


    public boolean getBooleanValue(String key) {
        return pref.getBoolean(key, false);
    }


    public void clear() {
        editor.clear().apply();
    }


    public void saveAppSettings(AppSettings data) {
        editor.putString(Const.Settings, new Gson().toJson(data));
        editor.apply();
    }

    public void saveFakeUsers(FakeUser data) {
        editor.putString(Const.FAKE_USER, new Gson().toJson(data));
        editor.apply();
    }

    public FakeUser getFakeUser() {
        String fakeUserString = pref.getString(Const.FAKE_USER, "");
        if (!fakeUserString.isEmpty()) {
            return new Gson().fromJson(fakeUserString, FakeUser.class);
        }
        return null;
    }


    public AppSettings getAppSettings() {
        String str = pref.getString(Const.Settings, "");
        if (str != null && !str.isEmpty()) {
            return new Gson().fromJson(str, AppSettings.class);
        }
        return null;
    }

    public void saveUser(User user) {
        editor.putString(Const.USER, new Gson().toJson(user));
        editor.apply();
    }

    public User getUser() {
        String userString = pref.getString(Const.USER, "");
        if (!userString.isEmpty()) {
            return new Gson().fromJson(userString, User.class);
        }
        return null;
    }

    public void manageWallet(boolean isIncrease, int coinAmount) {
        int userCoinAmount = getUser().getData().getCoins();
        if (isIncrease) {
            userCoinAmount += coinAmount;
        } else {
            userCoinAmount -= coinAmount;
        }
        User user = getUser();
        user.getData().setCoins(userCoinAmount);
        saveUser(user);
    }
}
