package me.blackphreak;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import me.blackphreak.Debug.Debug;
import me.blackphreak.Debug.DebugLevel;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class FileIO {
	public static void readConfig(String fullPathToConfigFile) {
		if (!fullPathToConfigFile.isEmpty()) {
			File config = new File(fullPathToConfigFile);
			if (!config.exists()) {
				// not a valid config file, but lets just continue.
				Debug.warn("Config file does not exist! Running in default config...");
			}
			else {
				// config file exists, load it.
				
				try {
					var reader = new JsonReader(new FileReader(config));
					Config.setInstance(new Gson().fromJson(reader, Config.class));
				}
				catch (Exception ex) {
					Debug.err(ex.getMessage());
					System.exit(1);
				}
			}
		}
		// else, run in default config
	}
	
	/**
	 * Save a config file with default config values
	 */
	public static void saveConfig() {
		File config = new File(Config.getInstance().baseFolder + "/config.json");
		try {
			JsonWriter writer = new JsonWriter(new FileWriter(config));
			new Gson().toJson(Config.getInstance(), Config.class, writer);
		}
		catch (IOException ex) {
			Debug.err("Failed to save config file. Error: " + ex.getMessage());
			return;
		}
		
		Debug.info("Configuration file saved.");
	}
	
	public static void initDir(String fullPathToBaseFolder) throws Exception {
		if (!fullPathToBaseFolder.isEmpty()) {
			Config.getInstance().baseFolder = fullPathToBaseFolder;
		}
		
		File tmp_baseFolder = new File(Config.getInstance().baseFolder);
		if (!tmp_baseFolder.exists() || !tmp_baseFolder.isDirectory()) {
			if (!tmp_baseFolder.mkdir()) {
				throw new Exception("Failed to create base directory");
			}
			else {
				Debug.info("Base directory created.");
			}
		}
		
		File tmp_dbFile = new File(Config.getInstance().dbFile);
		if (!tmp_dbFile.exists()) {
			Debug.info("Database does not exist. Copying default one.");
			
			if (!copy(
					Main.class.getResourceAsStream("students.db"),
					tmp_dbFile.getAbsolutePath()
				)
			) {
				throw new Exception("Failed to copy default database file.");
			}
			else {
				Debug.info("Default database copied. Using the default database...");
			}
		}
		
		Debug.log(DebugLevel.INFO.getLevel() | DebugLevel.DEBUG.getLevel(),
				0,
				"Directory initialization completed."
		);
	}
	
	
	// src  : https://stackoverflow.com/a/44077426
	// usage: copy(getClass().getResourceAsStream("/image/icon.png"), getBasePathForClass(Main.class)+"icon.png");
	private static boolean copy(InputStream source, String destination) {
		boolean isSuccess = true;
		
		try {
			Files.copy(source, Paths.get(destination), StandardCopyOption.REPLACE_EXISTING);
		} catch (IOException ex) {
			isSuccess = false;
		}
		
		return isSuccess;
	}
}
