/*
 * Copyright (C) 2025-2026  Tim Zimmermann <tim@aglais.org>
 *
 * 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 <http://www.gnu.org/licenses/>.
 */

package org.aglais.zms.ui.tab.species;

import org.aglais.zms.AglaisZMS;
import org.aglais.zms.db.core.model.AncestryData;
import org.aglais.zms.db.core.model.Species;
import org.aglais.zms.ui.component.MapPanel;
import org.aglais.zms.ui.map.RadiusWaypoint;
import org.aglais.zms.ui.map.RadiusWaypointRenderer;
import org.aglais.zms.ui.tab.SubTab;
import org.aglais.zms.ui.tab.SpeciesTab;
import org.aglais.zms.ui.util.SpeciesUtil;
import org.jetbrains.annotations.NotNull;
import org.jxmapviewer.viewer.GeoPosition;
import org.jxmapviewer.viewer.WaypointPainter;

import javax.swing.*;
import java.util.*;

/**
 * SpeciesOriginTab is a sub-tab component that displays geographical origin information
 * for a given species. It integrates with a map viewer to show the species' native
 * locations.
 */
public class SpeciesOriginTab extends SubTab<SpeciesTab> {
    private JPanel contentPane;
    private MapPanel map;
    private final WaypointPainter<RadiusWaypoint> waypointPainter = new WaypointPainter<>();

    /**
     * Constructs a new {@link SpeciesOriginTab}
     *
     * @param zms    The main application instance
     * @param parent The parent {@link SpeciesTab} containing this sub-tab
     */
    public SpeciesOriginTab(AglaisZMS zms, SpeciesTab parent) {
        super(zms, parent);

        waypointPainter.setRenderer(new RadiusWaypointRenderer());
        map.addOverlayPainter(waypointPainter);
        map.setAddressLocation(new GeoPosition(0, 0));
    }

    @Override
    public void onShow() {
        Species selectedSpecies = parent.getSelectedSpecies();
        List<AncestryData> ancestry = zms.getClient().getSpeciesAncestry(selectedSpecies);
        List<AncestryData> alive = new ArrayList<>();
        HashSet<AncestryData> ancestryToDraw = new HashSet<>();
        HashMap<Integer, AncestryData> idMap = new HashMap<>();

        // Collect all alive populations
        for (AncestryData data : ancestry) {
            idMap.put(data.getID(), data);

            if (SpeciesUtil.isPopulationAlive(data))
                alive.add(data);
        }

        // Add all ancestors of currently alive populations
        List<AncestryData> currentLayer = alive;
        while (!currentLayer.isEmpty()) {
            List<AncestryData> previousLayer = new ArrayList<>();

            ancestryToDraw.addAll(currentLayer);
            for (AncestryData data : currentLayer) {
                for (int parent : data.getParents())
                    previousLayer.add(idMap.get(parent));
            }

            currentLayer = previousLayer;
        }

        // Draw waypoints
        HashSet<RadiusWaypoint> waypoints = new HashSet<>();
        for (AncestryData data : ancestryToDraw) {
            Integer radius = data.getOriginRadius();
            GeoPosition position = null;
            if (data.getOriginLatitude() != null && data.getOriginLongitude() != null)
                position = new GeoPosition(data.getOriginLatitude(), data.getOriginLongitude());

            if (position != null)
                waypoints.add(new RadiusWaypoint(position, radius != null ? radius : 0));
        }
        waypointPainter.setWaypoints(waypoints);
        map.repaint();
        map.zoomTo(waypoints.toArray(new RadiusWaypoint[0]));
    }

    @Override
    public @NotNull JComponent getContentPane() {
        return contentPane;
    }
}