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

import de.steamwar.fightsystem.Config;
import de.steamwar.fightsystem.states.FightState;
import de.steamwar.fightsystem.states.StateDependent;
import de.steamwar.linkage.Linked;
import lombok.Getter;

import java.io.*;
import java.util.zip.GZIPOutputStream;

@Linked
public class FileRecorder extends StateDependent implements Recorder {

    @Getter
    private static final File file = new File(Config.world.getWorldFolder(), "recording.recording");
    private DataOutputStream outputStream;

    public FileRecorder() {
        super(Config.ReplayID == 0, FightState.Recording);
        register();
    }

    @Override
    public DataOutputStream getStream() {
        return outputStream;
    }

    @Override
    public void enable() {
        try {
            outputStream = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(file), 4096)) {
                @Override
                public synchronized void flush() {
                    //Don't flush explicitly (performance)
                }

                @Override
                public void close() throws IOException {
                    try {
                        super.flush();
                    } catch (IOException e) {
                        //do nothing
                    }
                    super.close();
                }
            });
        } catch (IOException e) {
            throw new SecurityException("Could not open file", e);
        }
        Recorder.super.enable();
    }

    @Override
    public void disable() {
        Recorder.super.disable();
    }
}
