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

import de.steamwar.bausystem.tracer.TNTPosition;
import org.bukkit.entity.TNTPrimed;

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

public class Record {

    private final long startTime;
    private final List<TNTRecord> tnt = new ArrayList<>();

    public int size() {
        return tnt.size();
    }

    public long getStartTime() {
        return startTime;
    }

    public void showAll(ShowMode mode) {
        for (TNTRecord record : tnt)
            record.showAll(mode);
    }

    /* The following methods should only be called by a recorder */
    public Record() {
        startTime = System.currentTimeMillis();
        StoredRecords.add(this);
    }

    public TNTRecord spawn() {
        TNTRecord record = new TNTRecord();
        tnt.add(record);
        return record;
    }

    public void clear() {
        tnt.clear();
    }

    public static class TNTRecord {
        private final List<TNTPosition> positions = new ArrayList<>(41);

        public void showAll(ShowMode mode) {
            for (TNTPosition position : positions)
                mode.show(position);
        }

        /* The following methods should only be called by a recorder */
        public void add(TNTPrimed tntPrimed) {
            add(tntPrimed, false);
        }

        private void add(TNTPrimed tntPrimed, boolean exploded) {
            TNTPosition position;
            if (positions.isEmpty()) {
                position = new TNTPosition(this, tntPrimed, null, exploded);
            } else {
                position = new TNTPosition(this, tntPrimed, positions.get(positions.size() - 1).getLocation(), exploded);
            }
            positions.add(position);
            TraceShowManager.show(position);
        }

        public void explode(TNTPrimed tntPrimed) {
            add(tntPrimed, true);
        }

        public List<TNTPosition> getPositions() {
            return positions;
        }
    }
}
