/*
    This file is a part of the SteamWar software.

    Copyright (C) 2020  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.tracer.record;

import de.steamwar.bausystem.BauSystem;
import org.bukkit.Bukkit;
import org.bukkit.entity.TNTPrimed;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.scheduler.BukkitTask;

public class TraceAutoHandler implements Listener {
    /* This listener handles the en- and disabling of the Tracer in AUTO mode */

    private BukkitTask task;
    private int lastExplosion = 0;  // Time since the last explosion in ticks

    public void enable() {
        Bukkit.getPluginManager().registerEvents(this, BauSystem.getPlugin());
    }

    public void disable() {
        HandlerList.unregisterAll(this);
        if (task != null) {
            task.cancel();
            task = null;
        }
    }

    @EventHandler
    public void onEntityExplode(EntityExplodeEvent event) {
        if (!(event.getEntity() instanceof TNTPrimed))
            return;

        lastExplosion = 0;
        if (task == null) {
            RecordStateMachine.autoRecord();
            task = Bukkit.getScheduler().runTaskTimer(BauSystem.getPlugin(), this::run, 1, 1);
        }
    }

    private void run() {
        lastExplosion++;

        if (lastExplosion > 80) {
            RecordStateMachine.autoIdle();
            task.cancel();
            task = null;
        }
    }
}
