/*
 *   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.features.simulator.gui;

import de.steamwar.bausystem.features.simulator.SimulatorWatcher;
import de.steamwar.bausystem.features.simulator.data.Simulator;
import de.steamwar.bausystem.features.simulator.data.SimulatorPhase;
import de.steamwar.bausystem.features.simulator.data.redstone.RedstoneElement;
import de.steamwar.bausystem.features.simulator.data.redstone.RedstonePhase;
import de.steamwar.bausystem.features.simulator.gui.base.SimulatorAnvilGui;
import de.steamwar.bausystem.features.simulator.gui.base.SimulatorBaseGui;
import de.steamwar.data.CMDs;
import de.steamwar.inventory.SWItem;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.ClickType;

import java.util.Arrays;

public class SimulatorRedstonePhaseSettingsGui extends SimulatorBaseGui {
    private final RedstoneElement redstoneElement;
    private final RedstonePhase redstone;
    private final SimulatorBaseGui back;

    public SimulatorRedstonePhaseSettingsGui(Player player, Simulator simulator, RedstoneElement redstoneElement, RedstonePhase redstone, SimulatorBaseGui back) {
        super(player, simulator, 5 * 9);
        this.redstoneElement = redstoneElement;
        this.redstone = redstone;
        this.back = back;
    }

    @Override
    public String title() {
        return "Redstone";
    }

    @Override
    public void populate() {
        if (!redstoneElement.getPhases().contains(redstone)) {
            back.open();
            return;
        }

        // Back Arrow
        inventory.setItem(0, new SWItem(Material.ARROW, "§eBack", clickType -> {
            back.open();
        }).setCustomModelData(CMDs.BACK));

        // Material Chooser
        inventory.setItem(4, redstoneElement.toItem(player, clickType -> {
            new SimulatorMaterialGui(player, simulator, redstoneElement::getMaterial, redstoneElement::setMaterial, this).open();
        }));

        // Delete
        inventory.setItem(8, new SWItem(Material.BARRIER, "§eDelete", clickType -> {
            redstoneElement.getPhases().remove(redstone);
            back.open();
            SimulatorWatcher.update(simulator);
        }).setCustomModelData(CMDs.Simulator.DELETE));

        int index = redstoneElement.getPhases().indexOf(redstone);
        int min;
        if (index > 0) {
            RedstonePhase previous = redstoneElement.getPhases().get(index - 1);
            min = previous.getTickOffset() + previous.getLifetime() + 1;
        } else {
            min = 0;
        }

        int maxLifetime;
        int maxOffset;
        if (index < redstoneElement.getPhases().size() - 1) {
            RedstonePhase next = redstoneElement.getPhases().get(index + 1);
            maxLifetime = next.getTickOffset() - redstone.getTickOffset() - 1;
            maxOffset = next.getTickOffset() - redstone.getLifetime() - 1;
        } else {
            maxLifetime = Integer.MAX_VALUE - 5;
            maxOffset = Integer.MAX_VALUE - 5;
        }

        //Tick Offset
        int offset = redstone.getTickOffset();
        inventory.setItem(10, new SWItem(offset < maxOffset ? Material.LIME_DYE : Material.GRAY_DYE, "§e+1", Arrays.asList("§7Shift§8: §e+5"), false, clickType -> {
            if (clickType == ClickType.DOUBLE_CLICK) return;
            redstone.setTickOffset(Math.min(maxOffset, offset + (clickType.isShiftClick() ? 5 : 1)));
            SimulatorWatcher.update(simulator);
        }).setCustomModelData(CMDs.Simulator.INCREMENT_OR_DISABLED));

        SWItem offsetItem = new SWItem(Material.REPEATER, "§eStart at§8:§7 " + offset, clickType -> {
            new SimulatorAnvilGui<>(player, "Start at", offset + "", Integer::parseInt, integer -> {
                if (integer < 0) return false;
                redstone.setTickOffset(Math.min(Math.max(integer, min), maxOffset));
                SimulatorWatcher.update(simulator);
                return true;
            }, this).setItem(Material.REPEATER).open();
        });
        offsetItem.getItemStack().setAmount(Math.max(1, Math.min(offset, 64)));
        inventory.setItem(19, offsetItem);

        inventory.setItem(28, new SWItem(offset > min ? Material.RED_DYE : Material.GRAY_DYE, "§e-1", Arrays.asList("§7Shift§8: §e-5"), false, clickType -> {
            if (clickType == ClickType.DOUBLE_CLICK) return;
            redstone.setTickOffset(Math.max(min, offset - (clickType.isShiftClick() ? 5 : 1)));
            SimulatorWatcher.update(simulator);
        }).setCustomModelData(CMDs.Simulator.DECREMENT_OR_DISABLED));

        //Lifetime
        int lifetime = redstone.getLifetime();
        inventory.setItem(11, new SWItem(lifetime < maxLifetime ? Material.LIME_DYE : Material.GRAY_DYE, "§e+1", Arrays.asList("§7Shift§8: §e+5"), false, clickType -> {
            if (clickType == ClickType.DOUBLE_CLICK) return;
            redstone.setLifetime(Math.min(maxLifetime, lifetime + (clickType.isShiftClick() ? 5 : 1)));
            SimulatorWatcher.update(simulator);
        }).setCustomModelData(CMDs.Simulator.INCREMENT_OR_DISABLED));

        SWItem lifetimeItem = new SWItem(Material.CLOCK, "§eActivation Time§8:§7 " + lifetime, clickType -> {
            new SimulatorAnvilGui<>(player, "Activation Time", lifetime + "", Integer::parseInt, integer -> {
                if (integer < 0) return false;
                redstone.setLifetime(Math.min(integer, maxLifetime));
                SimulatorWatcher.update(simulator);
                return true;
            }, this).setItem(Material.CLOCK).open();
        });
        lifetimeItem.getItemStack().setAmount(Math.max(1, Math.min(lifetime, 64)));
        inventory.setItem(20, lifetimeItem);

        inventory.setItem(29, new SWItem(lifetime > 0 ? Material.RED_DYE : Material.GRAY_DYE, "§e-1", Arrays.asList("§7Shift§8: §e-5"), false, clickType -> {
            if (clickType == ClickType.DOUBLE_CLICK) return;
            redstone.setLifetime(Math.max(0, lifetime - (clickType.isShiftClick() ? 5 : 1)));
            SimulatorWatcher.update(simulator);
        }).setCustomModelData(CMDs.Simulator.DECREMENT_OR_DISABLED));

        //Order
        int order = redstone.getOrder();
        inventory.setItem(13, new SWItem(order < SimulatorPhase.ORDER_LIMIT ? Material.LIME_DYE : Material.GRAY_DYE, "§e+1", Arrays.asList("§7Shift§8: §e+5"), false, clickType -> {
            if (clickType == ClickType.DOUBLE_CLICK) return;
            redstone.setOrder(Math.min(SimulatorPhase.ORDER_LIMIT, order + (clickType.isShiftClick() ? 5 : 1)));
            SimulatorWatcher.update(simulator);
        }).setCustomModelData(CMDs.Simulator.INCREMENT_OR_DISABLED));

        SWItem orderItem = new SWItem(order >= 0 ? Material.COMPASS : Material.RECOVERY_COMPASS, "§eActivation Order§8:§7 " + order, clickType -> {
            new SimulatorAnvilGui<>(player, "Activation Order", order + "", Integer::parseInt, integer -> {
                if (integer < -SimulatorPhase.ORDER_LIMIT) return false;
                if (integer > SimulatorPhase.ORDER_LIMIT) return false;
                redstone.setOrder(integer);
                SimulatorWatcher.update(simulator);
                return true;
            }, this).setItem(order >= 0 ? Material.COMPASS : Material.RECOVERY_COMPASS).open();
        });
        orderItem.getItemStack().setAmount(Math.max(1, Math.min(Math.abs(order), 30)));
        inventory.setItem(22, orderItem);

        inventory.setItem(31, new SWItem(order > -SimulatorPhase.ORDER_LIMIT ? Material.RED_DYE : Material.GRAY_DYE, "§e-1", Arrays.asList("§7Shift§8: §e-5"), false, clickType -> {
            if (clickType == ClickType.DOUBLE_CLICK) return;
            redstone.setOrder(Math.max(-SimulatorPhase.ORDER_LIMIT, order - (clickType.isShiftClick() ? 5 : 1)));
            SimulatorWatcher.update(simulator);
        }).setCustomModelData(CMDs.Simulator.DECREMENT_OR_DISABLED));
    }
}
