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

import com.sk89q.worldedit.regions.RegionSelector;
import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.shared.Pair;
import de.steamwar.bausystem.utils.WorldEditUtils;
import de.steamwar.linkage.Linked;
import de.steamwar.linkage.MinVersion;
import de.steamwar.sql.SteamwarUser;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.checkerframework.checker.units.qual.min;

import java.io.*;
import java.util.List;
import java.util.logging.Level;
import java.util.stream.Collectors;

@Linked
@MinVersion(18)
public class WorldEditSelectionSaver implements Listener {

    private File WORLD_EDIT_SELECTIONS = new File(Bukkit.getWorlds().get(0).getWorldFolder(), "world_edit_selections");

    {
       WORLD_EDIT_SELECTIONS.mkdir();
    }

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event) {
        SteamwarUser steamwarUser = SteamwarUser.get(event.getPlayer().getUniqueId());
        File file = new File(WORLD_EDIT_SELECTIONS, Integer.toString(steamwarUser.getId()));
        if (!file.exists()) return;
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            Class<? extends RegionSelector> clazz = (Class<? extends RegionSelector>) Class.forName(bufferedReader.readLine());
            List<Location> locations = bufferedReader.lines()
                    .map(s -> s.split(" "))
                    .map(strings -> strings.length != 3 ? null : new Location(event.getPlayer().getWorld(), Integer.parseInt(strings[0]), Integer.parseInt(strings[1]), Integer.parseInt(strings[2])))
                    .collect(Collectors.toList());
            WorldEditUtils.setVertices(event.getPlayer(), clazz, locations);
        } catch (IOException | ClassNotFoundException e) {
            BauSystem.getInstance().getLogger().log(Level.SEVERE, e.getMessage(), e);
            file.delete();
        }
    }

    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event) {
        SteamwarUser steamwarUser = SteamwarUser.get(event.getPlayer().getUniqueId());
        Pair<Class<? extends RegionSelector>, List<Location>> data = WorldEditUtils.getVertices(event.getPlayer());
        File file = new File(WORLD_EDIT_SELECTIONS, Integer.toString(steamwarUser.getId()));
        try {
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
            bufferedWriter.write(data.getKey().getTypeName());
            for (Location location : data.getValue()) {
                if (location == null) {
                    bufferedWriter.write("\n");
                } else {
                    bufferedWriter.write("\n" + location.getBlockX() + " " + location.getBlockY() + " " + location.getBlockZ());
                }
            }
            bufferedWriter.close();
        } catch (IOException e) {
            BauSystem.getInstance().getLogger().log(Level.SEVERE, e.getMessage(), e);
            file.delete();
        }
    }
}
