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

import de.steamwar.bausystem.features.tpslimit.TPSUtils;
import de.steamwar.bausystem.region.Region;
import lombok.Getter;
import lombok.SneakyThrows;

import java.util.ArrayList;
import java.util.List;

public class TraceRecordingWrapper {

    @Getter
    private final Trace trace;

    @Getter
    private final long startTick;
    private final List<TNTPoint> recordsToAdd;
    private final List<TNTPoint> recordList;
    private int nextOpenRecordId = 0;
    @Getter
    private boolean explosionRecorded = false;

    @SneakyThrows
    public TraceRecordingWrapper(Region region) {
        startTick = TPSUtils.currentRealTick.get();
        recordsToAdd = new ArrayList<>();
        recordList = new ArrayList<>();

        trace = new Trace(region, recordList);
    }

    public int getNextOpenRecordIdAndIncrement() {
        return nextOpenRecordId++;
    }

    public void activateExplosionRecorded() {
        explosionRecorded = true;
    }

    public void addRecord(TNTPoint record) {
        recordsToAdd.add(record);
    }

    public void commitRecorded() {
        TraceManager.instance.showPartial(trace, recordsToAdd);

        recordList.addAll(recordsToAdd);
        trace.setTntIdCount((int) recordList.stream().map(TNTPoint::getTntId).distinct().count());
        recordsToAdd.clear();
    }

    @SneakyThrows
    protected void finalizeRecording() {
        TraceRepository.writeTrace(trace, recordList);
        TraceManager.instance.add(trace);
    }
}
