package com.getbubblenow.android.repository;

import android.content.Context;

public final class CredentialRepository {

    private static final String CREDS_SHARED_PREFS_FILE_NAME = "creds";
    private static final String USERNAME_PROP = "username";
    private static final String SAGE_PASSWORD_PROP = "sagePassword";
    private static final String NODE_PASSWORD_PROP = "nodePassword";

    private static volatile CredentialRepository instance;

    private final Context context;

    private CredentialRepository(final Context context) {
        this.context = context;
    }

    public static CredentialRepository getInstance(final Context context) {
        if (instance == null) {
            synchronized (CredentialRepository.class) {
                if (instance == null) {
                    instance = new CredentialRepository(context);
                }
            }
        }
        return instance;
    }

    public String getUsername() {
        return context.getSharedPreferences(CREDS_SHARED_PREFS_FILE_NAME, Context.MODE_PRIVATE).getString(USERNAME_PROP, "");
    }

    public void setUsername(final String username) {
        context.getSharedPreferences(CREDS_SHARED_PREFS_FILE_NAME, Context.MODE_PRIVATE).edit().putString(USERNAME_PROP, username).apply();
    }

    public String getSagePassword() {
        return context.getSharedPreferences(CREDS_SHARED_PREFS_FILE_NAME, Context.MODE_PRIVATE).getString(SAGE_PASSWORD_PROP, "");
    }

    public void setSagePassword(final String sagePassword) {
        context.getSharedPreferences(CREDS_SHARED_PREFS_FILE_NAME, Context.MODE_PRIVATE).edit().putString(SAGE_PASSWORD_PROP, sagePassword).apply();
    }

    public String getNodePassword() {
        return context.getSharedPreferences(CREDS_SHARED_PREFS_FILE_NAME, Context.MODE_PRIVATE).getString(NODE_PASSWORD_PROP, "");
    }

    public void setNodePassword(final String nodePassword) {
        context.getSharedPreferences(CREDS_SHARED_PREFS_FILE_NAME, Context.MODE_PRIVATE).edit().putString(NODE_PASSWORD_PROP, nodePassword).apply();
    }

    public void clear() {
        context.getSharedPreferences(CREDS_SHARED_PREFS_FILE_NAME, Context.MODE_PRIVATE)
                .edit()
                .remove(USERNAME_PROP)
                .remove(SAGE_PASSWORD_PROP)
                .remove(NODE_PASSWORD_PROP)
                .apply();
    }
}
