/*
 * Copyright (C) 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.util;

import org.aglais.zms.AglaisZMS;
import org.aglais.zms.db.core.model.AncestryData;
import org.aglais.zms.db.core.model.Species;

import java.util.List;

/**
 * Helper class for retrieving additional species-related information.
 */
public class SpeciesUtil {

    /**
     * Get the currently alive populations count for a given {@link Species}
     *
     * @param zms     The {@link AglaisZMS} instance for querying ancestry data
     * @param species The species to query
     * @return The count of all populations which {@link #isPopulationAlive} returns true for,
     * a value of -1 indicates there are no populations at all
     */
    public static int getAlivePopulationsCount(AglaisZMS zms, Species species) {
        List<AncestryData> populations = zms.getClient().getSpeciesAncestry(species);
        if (populations.isEmpty())
            return -1;

        int populationsCount = 0;

        for (AncestryData population : populations) {
            if (isPopulationAlive(population)) {
                populationsCount++;
            }
        }

        return populationsCount;
    }

    /**
     * Check if a population is still alive
     *
     * @param population The population to check
     * @return True if there is no end date set or the end date is in the future
     */
    public static boolean isPopulationAlive(AncestryData population) {
        return population.getDateEnd() == null || population.getDateEnd().getTime() > System.currentTimeMillis();
    }
}
