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

import de.steamwar.bausystem.features.simulator.data.SimulatorPhase;
import de.steamwar.bausystem.features.simulator.execute.SimulatorAction;
import lombok.NoArgsConstructor;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.util.Vector;

import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;

@NoArgsConstructor
public final class RedstonePhase extends SimulatorPhase {

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

    {
        this.lifetime = 1;
    }

    @Override
    public void toSimulatorActions(Vector position, BiConsumer<Integer, SimulatorAction> tickStart, BiConsumer<Integer, SimulatorAction> tickEnd) {
        AtomicReference<BlockState> blockState = new AtomicReference<>();
        tickStart.accept(tickOffset, new SimulatorAction(order, 1) {
            @Override
            public void accept(World world) {
                Block block = world.getBlockAt(position.getBlockX(), position.getBlockY(), position.getBlockZ());
                blockState.set(block.getState());
                block.setType(Material.REDSTONE_BLOCK);
            }
        });
        tickStart.accept(tickOffset + lifetime, new SimulatorAction(ORDER_LIMIT + 1, 1) {
            @Override
            public void accept(World world) {
                BlockState state = blockState.get();
                if (state != null) {
                    state.update(true, true);
                } else {
                    Block block = world.getBlockAt(position.getBlockX(), position.getBlockY(), position.getBlockZ());
                    block.setType(Material.AIR);
                }
            }
        });
    }
}
