package tech.nevets.tvpn.auth;

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

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class Session {
    private static final Logger LOGGER = new Logger(Session.class);

    private final UserToken token;

    public static Session loadSession() {
        File f = new File(Utils.APP_DIR + "/session.json");
        if (f.exists() && f.isFile()) {
            Gson g = new Gson();
            try {
                BufferedReader br = Files.newBufferedReader(Path.of(Utils.APP_DIR + "/session.json"));
                return g.fromJson(br, Session.class);
            } catch (IOException e) {
                LOGGER.error(e.getMessage());
            }
        }
        return null;
    }

    public Session(UserToken token) {
        this.token = token;
        saveSession();
    }

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

    public void invalidateSession() {
        this.token.invalidate();
    }

    public void saveSession() {
        try {
            Files.writeString(Path.of(Utils.APP_DIR + "/session.json"), new Gson().toJson(token));
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
    }
}
