/*
 * Copyright (c) 2026 University of Insubria <https://www.uninsubria.it>
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or (at
 * your option) any later version. All we ask is that proper credit is given
 * for our work, which includes - but is not limited to - adding the above
 * copyright notice to the beginning of your source code files, and to any
 * copyright notice that you may distribute with programs based on this work.
 *
 * This library 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 Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation, Inc.
 * <https://fsf.org/>
 */

package qsardes.descriptor;

import qsardes.cdk.CdkBuilder;
import qsardes.molecule.AbstractMoleculeBuilder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import org.openscience.cdk.exception.CDKException;
import org.openscience.cdk.qsar.descriptors.molecular.AtomCountDescriptor;

/**
 * Atom count descriptors abstract class.
 *
 * @author Nicola Chirico
 */
public abstract class DescriptorAtomCount implements Descriptor
{
    protected DescriptorAtomCount()
    {
    }

    @Override
    public String toString()
    {
        return "Atom count";
    }

    @Override
    public DescriptorType get_descriptor_type()
    {
        return DescriptorType.valueOf("DESCRIPTOR");
    }

    @Override
    public List<String> get_descriptor_names()
    {
        List<String> list = new ArrayList<>();

        list.add("nHeavyAtom");

        atom_list.forEach(name -> {
            if (name.equals("*")) {
                list.add("nAtom");
            } else {
                list.add("n" + name);
            }
        });

        list.add("nX");

        return list;
    }

    @Override
    public Map<String, String> get_descriptor_values(
            AbstractMoleculeBuilder mol_build)
    {
        prepare_descr_map();

        try {
            descr_map.put("nHeavyAtom", count_heavy_atoms(mol_build));
            get_atoms_count(mol_build);
            descr_map.put("nX", count_halogens(mol_build));
        } catch (Exception ex) {
            System.err.println(ex);
        }

        return descr_map;
    }

    private void prepare_descr_map()
    {
        final String NAN = String.valueOf(Double.NaN);

        get_descriptor_names().forEach(name -> descr_map.put(name, NAN));
    }

    private String count_heavy_atoms(AbstractMoleculeBuilder mol_build)
    {
        int count = 0;

        for (String atom : atom_list) {
            if (atom.equals("H") || atom.equals("*")) {
                continue;
            }

            var iter = new CdkBuilder(new AtomCountDescriptor(),
                    new String[]{atom}, mol_build)
                    .calc_descr_impl_hydrogens().entrySet().iterator();

            if (iter.hasNext()) {
                count += Integer.valueOf(iter.next().getValue());
            }
        }

        return String.valueOf(count);
    }

    private void get_atoms_count(AbstractMoleculeBuilder mol_build)
    {
        for (String atom : atom_list) {
            descr_map.putAll(new CdkBuilder(new AtomCountDescriptor(),
                    new String[]{atom}, mol_build)
                    .calc_descr_impl_hydrogens());
        }
    }

    private String count_halogens(AbstractMoleculeBuilder mol_build)
    {
        try {
            int count = get_atom_count(mol_build, "F");

            count += get_atom_count(mol_build, "Cl");
            count += get_atom_count(mol_build, "Br");
            count += get_atom_count(mol_build, "I");
            count += get_atom_count(mol_build, "At");
            count += get_atom_count(mol_build, "Uus");

            return String.valueOf(count);
        } catch (CDKException | NoSuchElementException ex) {
            System.err.println(ex);
            return String.valueOf(Double.NaN);
        }
    }

    private int get_atom_count(AbstractMoleculeBuilder mol_build,
            String atom) throws CDKException
    {
        var iter = new CdkBuilder(new AtomCountDescriptor(),
                new String[]{atom}, mol_build)
                .calc_descr_impl_hydrogens().entrySet().iterator();

        return iter.hasNext() ? Integer.parseInt(iter.next().getValue()) : 0;
    }

    private final List<String> atom_list = Arrays.asList(
            "*", "H", "B", "C", "N", "O", "S", "P", "F", "Cl", "Br", "I");

    private final Map<String, String> descr_map = new HashMap<>();
}
