/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2025 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.bausystem.worlddata;

import lombok.experimental.UtilityClass;
import org.bukkit.Bukkit;
import yapion.hierarchy.output.FileOutput;
import yapion.hierarchy.types.YAPIONObject;
import yapion.parser.InputStreamCharsets;
import yapion.parser.YAPIONParser;
import yapion.parser.options.StreamOptions;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@UtilityClass
public class WorldData {

    private final File optionsFile = new File(Bukkit.getWorlds().get(0).getWorldFolder(), "options.yapion");
    private YAPIONObject worldData;

    public YAPIONObject getWorldData() {
        if (worldData == null) {
            read();
        }
        return worldData;
    }

    public YAPIONObject getRegionsData() {
        return getWorldData().getYAPIONObjectOrSetDefault("regions", new YAPIONObject());
    }

    public YAPIONObject getWarpData() {
        return getWorldData().getYAPIONObjectOrSetDefault("warps", new YAPIONObject());
    }

    private void read() {
        worldData = new YAPIONObject();
        if (optionsFile.length() != 0) {
            try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(optionsFile))) {
                worldData = YAPIONParser.parse(bufferedInputStream, new StreamOptions().charset(InputStreamCharsets.UTF_8));
            } catch (IOException e) {
                // Ignored
            }
        } else {
            write();
        }
    }

    public void write() {
        try {
            worldData.toYAPION(new FileOutput(optionsFile)).close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
