import csv
import logging

from .base import DataSource

log = logging.getLogger(__name__)


class CsvDataSource(DataSource):
    """
    Datasource for CSV tables

    A csv table is actually any text-delimited file (like comma, tab etc.)
    The datasource defaults to ',' as a delimiter, but can be given any other delimiter in the settings.

    An example settings object (with custom ';' delimiter)

    settings = {
        'datasource_type': 'csv',
        'csv_file': '/tmp/data/notatio_csv/notatio_waarnemingen.csv',
        'csv_delimiter': ';'
    }

    Note that this datasource is only of use in (R and CLI)-scripts. It's much easier to load a table in QGIS
    """

    def __init__(self, settings: dict = None):
        """
        Constructor

        :param dict settings: settings object with needed parameter keys/values (see above)
        """
        super().__init__(settings)
        if settings is None:
            self.settings = {}
        log.debug(f"Init CsvDataSource, settings: {self.settings}")
        self.file = None
        self.csv_file = None
        self.csv_reader = None
        self.delimiter = ","
        self._set_settings()

    def get_records(self):
        """
        Get all records as an iterator

        :return: iterator to call '.next()' on to retrieve record one by one
        """
        log.info(f"Reading records from: {self.file}")
        with open(
            self.file, newline="", mode="r", encoding="utf-8-sig"
        ) as self.csv_file:
            # Normal reader, returns a list of every row, but we use a DictReader
            # csv_reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
            # DictReader, returns a dictionary
            self.csv_reader = csv.DictReader(
                self.csv_file, delimiter=self.delimiter, skipinitialspace=True
            )
            for row in self.csv_reader:
                # print(f'{type(row)} {row}')
                yield row

    def _set_settings(self):
        if "csv_file" in self.settings:
            self.file = self.settings["csv_file"]
        if "csv_delimiter" in self.settings:
            self.delimiter = self.settings["csv_delimiter"]
        else:
            self.delimiter = ","  # defaulting to ,
