/*
 *   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.data.observer;

import de.steamwar.bausystem.features.simulator.data.SimulatorPhase;
import de.steamwar.bausystem.features.simulator.execute.SimulatorAction;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.data.type.Observer;
import org.bukkit.util.Vector;
import yapion.hierarchy.types.YAPIONObject;

import java.util.function.BiConsumer;

@NoArgsConstructor
public final class ObserverPhase extends SimulatorPhase {

    @Getter
    @Setter
    private BlockFace orientation = BlockFace.UP;

    public ObserverPhase(int tickOffset) {
        this.tickOffset = tickOffset;
    }

    {
        this.lifetime = 0;
    }

    @Override
    public void toSimulatorActions(Vector position, BiConsumer<Integer, SimulatorAction> tickStart, BiConsumer<Integer, SimulatorAction> tickEnd) {
        Observer observer = (Observer) Material.OBSERVER.createBlockData();
        observer.setFacing(orientation.getOppositeFace());
        observer.setPowered(true);

        tickStart.accept(tickOffset, new SimulatorAction(order, 1) {
            @Override
            public void accept(World world) {
                Block block = world.getBlockAt(position.getBlockX(), position.getBlockY(), position.getBlockZ());
                Block updateBlock = block.getRelative(orientation);
                BlockState state = updateBlock.getState();
                updateBlock.setType(Material.SPONGE, true);
                block.setBlockData(observer, true);
                state.update(true, true);
            }
        });
    }

    @Override
    public void saveExtra(YAPIONObject phaseObject) {
        phaseObject.add("orientation", orientation.name());
    }

    @Override
    public void loadExtra(YAPIONObject phaseObject) {
        orientation = BlockFace.valueOf(phaseObject.getPlainValue("orientation"));
    }
}
