/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2024  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.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPOutputStream;

public class TraceRecordingWrapper {

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

    @Getter
    private final Trace trace;

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

        trace = new Trace(region, recordList);
        File recordsSaveFile = new File(TraceManager.tracesFolder, trace.getUuid() + ".records");
        recordsOutputStream = new ObjectOutputStream(new GZIPOutputStream(new FileOutputStream(recordsSaveFile)));
    }

    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);

        recordsToAdd.forEach(record -> {
            try {
                recordsOutputStream.writeObject(record);
                recordsOutputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

        recordList.addAll(recordsToAdd);
        recordsToAdd.clear();
    }

    @SneakyThrows
    protected void finalizeRecording() {
        recordsOutputStream.flush();
        recordsOutputStream.close();
        TraceManager.instance.add(trace);
    }
}
