/*
 *   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 org.bukkit.Bukkit;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;

public class GlobalRecorder extends OutputStream implements Recorder {

    private static final GlobalRecorder recorder = new GlobalRecorder();

    public static GlobalRecorder getInstance(){
        return recorder;
    }

    private final List<Recorder> recorders = new ArrayList<>();
    private final DataOutputStream outputStream = new DataOutputStream(this);

    public void add(Recorder recorder){
        recorders.add(recorder);
    }

    public void remove(Recorder recorder){
        recorders.remove(recorder);
    }
    
    public boolean recording(){
        return !recorders.isEmpty();
    }

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

    @Override
    public void write(int i) {
        foreach(stream -> stream.write(i));
    }

    @Override
    public void write(byte[] bytes, int i, int i1) {
        foreach(stream -> stream.write(bytes, i, i1));
    }

    @Override
    public void flush() {
        foreach(OutputStream::flush);
    }

    @Override
    public void close() {
        foreach(OutputStream::close);
    }

    private void foreach(IOThrower thrower) {
        for(int i = 0; i < recorders.size(); i++) {
            Recorder stream = recorders.get(i);
            try{
                thrower.run(stream.getStream());
            }catch (IOException e){
                Bukkit.getLogger().log(Level.SEVERE, "Could not operate on OutputStream", e);
                stream.disable();
                i--; // Recorder was removed from recorders
            }
        }
    }

    interface IOThrower{
        void run(OutputStream stream) throws IOException;
    }
}
