"""Module for the conversion of coordinate files to library-workable objects

functions:
confs_to_mol_list: Converts the conformers inside a rdkit mol object to a list
    of separate mol objects.
rdkit_mol_to_ase_atoms: Converts a rdkit mol object into ase Atoms object.
adapt_format: Converts the coordinate files into a required library object type
"""

import logging

import rdkit.Chem.AllChem as Chem

logger = logging.getLogger('DockOnSurf')


def confs_to_mol_list(mol: Chem.rdchem.Mol, idx_lst=None):
    """Converts the conformers inside a rdkit mol object to a list of
    separate mol objects.

    @param mol: rdkit mol object containing at least one conformer.
    @param idx_lst:
    @return: list of separate mol objects.
    """
    if idx_lst is None:
        idx_lst = list(range(mol.GetNumConformers()))
    return [Chem.MolFromMolBlock(Chem.MolToMolBlock(mol, confId=int(idx)),
                                 removeHs=False) for idx in idx_lst]


def rdkit_mol_to_ase_atoms(mol: Chem.rdchem.Mol):
    """Converts a rdkit mol object into ase Atoms object.
    @param mol: rdkit mol object containing only one conformer.
    @return ase.Atoms: ase Atoms object with the same coordinates.
    """
    from ase import Atoms
    symbols = [atm.GetSymbol() for atm in mol.GetAtoms()]
    positions = mol.GetConformer(0).GetPositions()
    return Atoms(symbols=symbols, positions=positions)


def adapt_format(requirement, coord_file):
    """Converts the coordinate files into a required library object type.

    Depending on the library required to use and the file type, it converts the
    coordinate file into a library-workable object.
    @param requirement: str, the library for which the conversion should be
    made. Accepted values: 'ase', 'rdkit'.
    @param coord_file: str, path to the coordinates file aiming to convert.
    Accepted file tyoes: 'xyz', 'mol'.
    @return: an object the required library can work with.
    """
    from ase.io.formats import filetype

    req_vals = ['rdkit', 'ase']
    file_type_vals = ['xyz', 'mol']
    lib_err = f"The conversion to the '{requirement}' library object type" \
              f" has not yet been implemented"
    conv_info = f"Converted {coord_file} to {requirement} object type"

    fil_type_err = f'The {filetype(coord_file)} file formnat is not supported'

    if requirement not in req_vals:
        logger.error(lib_err)
        raise NotImplementedError(lib_err)

    if filetype(coord_file) not in file_type_vals:
        logger.error(fil_type_err)
        raise NotImplementedError(fil_type_err)

    if requirement == 'rdkit':
        if filetype(coord_file) == 'xyz':
            from xyz2mol import read_xyz_file, xyz2mol
            atoms, charge, xyz_coordinates = read_xyz_file(coord_file)
            rd_mol_obj = xyz2mol(atoms, xyz_coordinates, charge=charge)
            logger.debug(conv_info)
            return rd_mol_obj
        elif filetype(coord_file) == 'mol':
            from rdkit.Chem import MolFromMolFile
            logger.debug(conv_info)
            return MolFromMolFile(coord_file, removeHs=False)

    if requirement == 'ase':
        import ase.io
        logger.debug(conv_info)
        return ase.io.read(coord_file)
