/*
 * 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;

import de.steamwar.bausystem.tracer.AbstractTraceEntity;
import net.minecraft.server.v1_12_R1.*;
import org.bukkit.World;
import org.bukkit.craftbukkit.v1_12_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_12_R1.entity.CraftPlayer;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;

class TraceEntity12 extends EntityFallingBlock implements AbstractTraceEntity {

    private boolean exploded;
    private int references;

    public TraceEntity12(World world, Vector position, boolean tnt) {
        super(((CraftWorld) world).getHandle(), position.getX(), position.getY(), position.getZ(), tnt ? Blocks.TNT.getBlockData() : Blocks.STAINED_GLASS.getBlockData());

        this.setNoGravity(true);
        this.ticksLived = -12000;
    }

    @Override
    public void display(Player player, boolean exploded) {
        if (!this.exploded && exploded) {
            this.setCustomNameVisible(true);
            this.setCustomName("Bumm");
            this.exploded = true;
            if (references++ > 0)
                sendDestroy(player);
        } else if (references++ > 0)
            return;

        PacketPlayOutSpawnEntity packetPlayOutSpawnEntity = new PacketPlayOutSpawnEntity(this, 70, Block.getCombinedId(getBlock()));
        PlayerConnection playerConnection = ((CraftPlayer) player).getHandle().playerConnection;
        playerConnection.sendPacket(packetPlayOutSpawnEntity);

        PacketPlayOutEntityMetadata packetPlayOutEntityMetadata = new PacketPlayOutEntityMetadata(getId(), datawatcher, true);
        playerConnection.sendPacket(packetPlayOutEntityMetadata);

    }

    @Override
    public boolean hide(Player player, boolean force) {
        if (!force && --references > 0)
            return false;

        sendDestroy(player);
        die();
        return true;
    }

    private void sendDestroy(Player player) {
        PacketPlayOutEntityDestroy packetPlayOutEntityDestroy = new PacketPlayOutEntityDestroy(getId());
        ((CraftPlayer) player).getHandle().playerConnection.sendPacket(packetPlayOutEntityDestroy);
    }

}
