package tech.nevets.tvpn.auth;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import tech.nevets.tvpn.Utils;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

import static tech.nevets.tvpn.Utils.API_ENDPOINT_BASE;

public class UserToken {

    private boolean isAuthenticated;
    private final String token;
    private final long expires;
    private final String message;

    private String username;
    private String email;

    public UserToken(boolean isAuthenticated, String token, long expires, String message) {
        this.isAuthenticated = isAuthenticated;
        this.token = token;
        this.expires = expires;
        this.message = message;

        getUserInfo(token);
    }

    private void getUserInfo(String userToken) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "Bearer " + userToken);
        String response = Utils.get(URI.create(API_ENDPOINT_BASE + "api/user-info.php"), headers);
        JsonObject resObj = new Gson().fromJson(response, JsonObject.class);

        this.username = resObj.get("username").getAsString();
        this.email = resObj.get("email").getAsString();
    }

    public boolean isAuthenticated() {
        return this.isAuthenticated;
    }

    public void invalidate() {
        this.isAuthenticated = false;
    }

    public void checkExpiry() {
        if (System.currentTimeMillis() > expires) isAuthenticated = false;
    }

    public String getToken() {
        return this.token;
    }

    public String getMessage() {
        return this.message;
    }

    public String getUsername() {
        return this.username;
    }

    public String getEmail() {
        return this.email;
    }
}
