'''
.. Copyright (c) 2019 Richard Plevin
   See the https://opensource.org/licenses/MIT for license details.
'''
from .error import PygcamException, FileMissingError
from .log import getLogger
import os

_logger = getLogger(__name__)

_csvCache = {}

def readCachedCsv(filename, skiprows=1, cache=False):
    """
    Read a CSV file of the form generated by GCAM batch queries, i.e., skip one
    row and then read column headings and data. Optionally drop all years outside
    the `years` given. Optionally, linearly interpolate annual values between
    time-steps.

    :param filename: (str) the path to a CSV file
    :param skiprows: (int) the number of rows to skip before reading the data matrix
    :param cache: (bool) If True, file will be sought in, and saved to, a CSV cache.
       The "raw" file data is cached, so if called with different processing args,
       the same initial DataFrame is used, but it will be processed correctly.
    :return: (DataFrame) the data read in, processed as per arguments
    """
    import pandas as pd

    found = False

    if cache and filename in _csvCache:
        _logger.debug("Found %s in CSV cache", filename)
        df = _csvCache[filename]
        found = True

    else:
        try:
            _logger.debug("Reading %s", filename)
            df = pd.read_table(filename, sep=',', skiprows=skiprows, index_col=None)

        except IOError as e:
            raise FileMissingError(os.path.abspath(filename), e)

        except Exception as e:
            raise PygcamException('Error reading %s: %s' % (filename, e))

    # Cache a copy, unless it was already in the cache
    if cache and not found:
        _csvCache[filename] = df.copy()

    return df
