package com.browser;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.*;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.List;

public class DataManager {
    private static final String DATA_DIR = System.getProperty("user.home") + "/.javabrowser";
    private static final String BOOKMARKS_FILE = DATA_DIR + "/bookmarks.json";
    private static final String HISTORY_FILE = DATA_DIR + "/history.json";
    private static final String SETTINGS_FILE = DATA_DIR + "/settings.json";
    private final Gson gson = new Gson();

    public DataManager() {
        try {
            Files.createDirectories(Paths.get(DATA_DIR));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public List<String> loadBookmarks() {
        return loadList(BOOKMARKS_FILE);
    }

    public void saveBookmarks(List<String> bookmarks) {
        saveList(BOOKMARKS_FILE, bookmarks);
    }

    public List<String> loadHistory() {
        return loadList(HISTORY_FILE);
    }

    public void saveHistory(List<String> history) {
        saveList(HISTORY_FILE, history);
    }

    public String loadSearchEngine() {
        try {
            String content = Files.readString(Paths.get(SETTINGS_FILE));
            Settings settings = gson.fromJson(content, Settings.class);
            return settings != null && settings.searchEngine != null ? settings.searchEngine : "Google";
        } catch (IOException e) {
            return "Google";
        }
    }

    public void saveSearchEngine(String engine) {
        try {
            Settings settings = new Settings();
            settings.searchEngine = engine;
            Files.writeString(Paths.get(SETTINGS_FILE), gson.toJson(settings));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private List<String> loadList(String file) {
        try {
            String content = Files.readString(Paths.get(file));
            List<String> list = gson.fromJson(content, new TypeToken<List<String>>(){}.getType());
            return list != null ? new ArrayList<>(list) : new ArrayList<>();
        } catch (IOException e) {
            return new ArrayList<>();
        }
    }

    private void saveList(String file, List<String> list) {
        try {
            Files.writeString(Paths.get(file), gson.toJson(list));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static class Settings {
        String searchEngine;
    }
}
