"""_____________________________________________________________________

:PROJECT: ChemDataReader

* chemdatareader implementation *

:details:  chemdatareader implementation.

.. note:: -
.. todo:: - 
________________________________________________________________________
"""

import csv
import asyncio
from chemdatareader.chemdatareader_logger import get_logger

import chemdatareader.chemdatacollector_builder_interface as cdbi
import chemdatareader.collectors.pubchem_collector

import chemdatareader.chemdatareader_interface as cdri


class ChemDatReader(cdri.ChemDatReaderInterface):
    """Implementation of the ChemDatReader Interface"""

    def __init__(self) -> None:
        self.logger = get_logger(__name__)

        self.substance_name_list = []
        self.pubchem_service = cdbi.services.get("pubchem", pubchem_client_key="key", pubchem_client_secret="secret")

    def test_connections(self) -> str:
        """connection test module

        :param name: person to greet
        :type name: str
        """
        self.logger.debug(f"connection to : {self.pubchem_service.test_connection()}")
        return self.pubchem_service.test_connection()
    
    async def get_compounds_by_name(self, name_list: list[str] = [], operation: str = "record", output_format: str = "JSON"):
        """
        get all compounds of a list of names or CAS numbers
        """
        self.compound_list = []
        self.operation = operation
        self.output_format = output_format

        await self.pubchem_service.get_compounds_by_name(name_list, operation, output_format)
    
        return self.pubchem_service.compound_list

    async def read_substance_names_csv(self, csv_filename: str = None, column_name: str = None) -> None:
        """csv reader module
        :param: csv_filename: filename of the csv file
        :type: csv_filename: str
        """

        self.logger.debug(f"csv_filename : {csv_filename}")
        try:
            with open(csv_filename, newline="") as csvfile:
                reader = csv.DictReader(csvfile)
                for row in reader:
                    self.logger.debug(f"row {row}")
                    self.logger.debug(f"{column_name}: {row[column_name] }")

                    self.substance_name_list.append(row[column_name])

            self.logger.debug(f"namelist: {self.substance_name_list}")
            await self.pubchem_service.get_compounds_by_name(self.substance_name_list)

            #self.logger.debug(f"compound_list: {compound_list}")

            #return compound_list

        except FileNotFoundError:
            self.logger.error(f"csv file {csv_filename} not found !")
            raise FileNotFoundError
        except KeyError:
            self.logger.error(f"csv file {csv_filename} has no CAS column !")
            raise KeyError
        except Exception as e:
            self.logger.error(f"csv file {csv_filename} has an error !")
            raise e
