/*
 * This file is a part of the SteamWar software.
 *
 * Copyright (C) 2021  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.region.loader;

import de.steamwar.bausystem.region.Prototype;
import lombok.experimental.UtilityClass;
import org.bukkit.Bukkit;
import yapion.hierarchy.diff.DiffDelete;
import yapion.hierarchy.diff.YAPIONDiff;
import yapion.hierarchy.types.YAPIONObject;
import yapion.parser.YAPIONParser;

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

@UtilityClass
public class PrototypeLoader {

    private YAPIONObject loaded = null;
    public static final File file = new File(Bukkit.getWorlds().get(0).getWorldFolder(), "prototypes.yapion");

    public void load() {
        YAPIONObject yapionObject = null;
        try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file))) {
            yapionObject = YAPIONParser.parse(bufferedInputStream);
        } catch (IOException e) {
            throw new SecurityException(e.getMessage(), e);
        }

        if (loaded != null && new YAPIONDiff(loaded, yapionObject).getDiffs().stream().anyMatch(DiffDelete.class::isInstance)) {
            throw new SecurityException("Version was not the specified version needed.");
        }
        loaded = yapionObject;

        yapionObject.forEach((key, yapionAnyType) -> {
            if (yapionAnyType instanceof YAPIONObject) {
                new Prototype(key, (YAPIONObject) yapionAnyType);
            }
        });
    }
}
