/*
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
 */
package com.mycompany.sigge;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.net.HttpURLConnection;
import java.net.URL;

public class ConfigManager {

	private static final Path APP_DIR =
		Paths.get(System.getProperty("user.home") , ".sigge");
	private static final Path CONFIG_FILE
		= APP_DIR.resolve("config.bin");
	private static final String RELOGIN_URL
		= "https://demo.iuvade.com/sigge/api/reloginW/";

	public static void saveConfig(AppConfig config) throws IOException {
		Files.createDirectories(APP_DIR);
		try (ObjectOutputStream oos
			= new ObjectOutputStream(new FileOutputStream(CONFIG_FILE.toFile()))) {
			oos.writeObject(config);
		}
	}

	public static AppConfig loadConfig() throws IOException, ClassNotFoundException {
		if (!Files.exists(CONFIG_FILE)) {
			return null;
		}

		try (ObjectInputStream ois =
			new ObjectInputStream(
			 new FileInputStream(CONFIG_FILE.toFile()))) {
			return (AppConfig) ois.readObject();
		}
	}

	public static boolean isLoggedIn(){
		try{
			AppConfig config = loadConfig();
			if(config == null || config.getAuthToken()==null){
				return false;
			}
			URL url = new URL(RELOGIN_URL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Authorization","Bearer"+config.getAuthToken());
			int status = conn.getResponseCode();
			if(status != 200){
				deleteConfig();
				return false;
			}
			return true;
			
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}

	public static void deleteConfig() {
		try {
			Files.deleteIfExists(CONFIG_FILE);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

