package me.echeung.listenmoeapi.auth;

import android.content.Context;
import android.preference.PreferenceManager;

/**
 * Helper for handling authorization-related tasks. Helps with the storage of the auth token and
 * actions requiring it.
 */
public class AuthUtil {

    private static final String USER_TOKEN = "user_token";
    private static final String LAST_AUTH = "last_auth";

    private String mfaToken;

    private Context context;

    public AuthUtil(Context context) {
        this.context = context;
    }

    /**
     * Checks if the user has previously logged in (i.e. a token is stored).
     *
     * @return Whether the user is authenticated.
     */
    public boolean isAuthenticated() {
        return getAuthToken() != null;
    }

    /**
     * Checks how old the stored auth token is. If it's older than 28 days, it becomes invalidated.
     *
     * @return Whether the token is still valid.
     */
    public boolean checkAuthTokenValidity() {
        if (!isAuthenticated()) {
            return false;
        }

        // Check token is valid (max 28 days)
        final long lastAuth = getTokenAge();
        if (Math.round((System.currentTimeMillis() / 1000 - lastAuth) / 86400.0) >= 28) {
            clearAuthToken();
            return false;
        }

        return true;
    }

    /**
     * Fetches the stored temporary MFA auth token with the "Bearer" prefix.
     *
     * @return The temporary MFA auth token with the "Bearer" prefix.
     */
    public String getMfaAuthTokenWithPrefix() {
        return getPrefixedToken(mfaToken);
    }

    /**
     * Stores the temporary auth token for MFA.
     *
     * @param token The auth token for MFA to store, provided via the LISTEN.moe API.
     */
    public void setMfaAuthToken(String token) {
        this.mfaToken = token;
    }

    /**
     * Removes the stored temporary MFA auth token.
     */
    public void clearMfaAuthToken() {
        this.mfaToken = null;
    }

    /**
     * Fetches the stored auth token with the "Bearer" prefix.
     *
     * @return The user's auth token with the "Bearer" prefix.
     */
    public String getAuthTokenWithPrefix() {
        return getPrefixedToken(getAuthToken());
    }

    /**
     * Stores the auth token, also tracking the time that it was stored.
     * Android context to fetch SharedPreferences.
     *
     * @param token The auth token to store, provided via the LISTEN.moe API.
     */
    public void setAuthToken(String token) {
        PreferenceManager.getDefaultSharedPreferences(context)
                .edit()
                .putString(USER_TOKEN, token)
                .putLong(LAST_AUTH, System.currentTimeMillis() / 1000)
                .apply();
    }

    /**
     * Removes the stored auth token.
     */
    public void clearAuthToken() {
        PreferenceManager.getDefaultSharedPreferences(context)
                .edit()
                .putString(USER_TOKEN, null)
                .putLong(LAST_AUTH, 0)
                .apply();
    }

    private String getAuthToken() {
        return PreferenceManager.getDefaultSharedPreferences(context)
                .getString(USER_TOKEN, null);
    }

    private String getPrefixedToken(String token) {
        return String.format("Bearer %s", token);
    }

    /**
     * @return The time in seconds since the stored auth token was stored.
     */
    private long getTokenAge() {
        return PreferenceManager.getDefaultSharedPreferences(context)
                .getLong(LAST_AUTH, 0);
    }

}

@@ -110,16 +110,53 @@
 nager;%0A%0A
+import java.lang.ref.WeakReference;%0A%0A
 /**%0A * H
@@ -461,31 +461,46 @@
 private 
+WeakReference%3C
 Context
+%3E
  context
 ;%0A%0A    p
@@ -491,16 +491,19 @@
  context
+Ref
 ;%0A%0A    p
@@ -560,18 +560,42 @@
 text
- = 
+Ref = new WeakReference%3C%3E(
 context
+)
 ;%0A  
@@ -2565,32 +2565,144 @@
 String token) %7B%0A
+        final Context context = contextRef.get();%0A        if (context == null) %7B%0A            return;%0A        %7D%0A%0A
         Preferen
@@ -2740,32 +2740,32 @@
 rences(context)%0A
-
                 
@@ -3003,32 +3003,144 @@
 arAuthToken() %7B%0A
+        final Context context = contextRef.get();%0A        if (context == null) %7B%0A            return;%0A        %7D%0A%0A
         Preferen
@@ -3355,32 +3355,149 @@
 etAuthToken() %7B%0A
+        final Context context = contextRef.get();%0A        if (context == null) %7B%0A            return null;%0A        %7D%0A%0A
         return P
@@ -3832,24 +3832,139 @@
 okenAge() %7B%0A
+        final Context context = contextRef.get();%0A        if (context == null) %7B%0A            return 0L;%0A        %7D%0A%0A
         retu
@@ -4013,32 +4013,32 @@
 rences(context)%0A
-
                 
@@ -4058,16 +4058,17 @@
 _AUTH, 0
+L
 );%0A    %7D

Fix potential memory leak