from pathlib import Path

import numpy as np
import pandas as pd

from .io import config


def read_cumulative_iss_index():
    "Read in the whole cumulative index and return dataframe."
    try:
        indexdir = Path(config['pyciss_index']['path'])
    except KeyError:
        print("Did not find the key `[pyciss_index][path]` in the config file.")
        return
    path = indexdir / 'cumindex.tab.hdf'
    df = pd.read_hdf(path, 'df')
    # replace DPS Nan values (-1e32) with real NaNs
    return df.replace(-1.000000e+32, np.nan)


def read_ring_images_index():
    """Filter cumulative index for ring images.

    This is done by matching the column TARGET_DESC to contain the string 'ring'

    Returns
    -------
    pandas.DataFrame
        data table containing only meta-data for ring images
    """
    meta = read_cumulative_iss_index()
    ringfilter = meta.TARGET_DESC.str.contains('ring', case=False)
    return meta[ringfilter]


#
# def
#     else:
#         df = index_to_df(indexdir / 'cumindex.tab')
#         df.to_hdf(savepath, 'df')
#         return df
#

class IndexDB(object):
    def __init__(self, indexdir=None):
        if indexdir is None:
            try:
                indexdir = config['pyciss_index']['path']
            except KeyError:
                print("Did not find the key `pyciss_indexdir` in the config file.")
                return
        self.indexdir = Path(indexdir)

    @property
    def indexfiles(self):
        return self.indexdir.glob('*_????.tab')

    @property
    def cumulative_label(self):
        return IndexLabel(self.indexdir / 'cumindex.lbl')

    def get_index_no(self, no):
        return iss_index_to_df(next(self.indexdir.glob('*_' + str(no) + '.tab')))

@@ -403,16 +403,137 @@
 ab.hdf'%0A
+    try:%0A        df = pd.read_hdf(path, 'df')%0A    except FileNotFoundError:%0A        path = indexdir / 'cumindex.hdf'%0A    
     df =
@@ -553,24 +553,24 @@
 path, 'df')%0A
-
     # replac
@@ -1071,124 +1071,806 @@
 %5D%0A%0A%0A
-#%0A# def%0A#     else:%0A#         df = index_to_df(indexdir / 'cumindex.tab')%0A#         df.to_hdf(savepath, 'df')%0A#     
+def get_clearnacs_ring_images():%0A    df = read_ring_images_index()%0A    df%5Bdf == -1e32%5D = np.nan%0A    df = df.set_index('isotime')%0A    ringimages = df.query(%22RINGS_FLAG=='YES'%22)%0A    ringimages = ringimages%5Bringimages.MAXIMUM_RING_RADIUS.notnull()%5D%0A    ringimages = ringimages%5Bringimages.MINIMUM_RING_RADIUS.notnull()%5D%0A    ringimages = ringimages.query('MAXIMUM_RING_RADIUS %3C 1e90 and MINIMUM_RING_RADIUS %3E 0')%0A    nac = ringimages%5Bringimages.INSTRUMENT_ID == 'ISSNA'%5D%0A    clearnacs = nac.query('FILTER_NAME_1 == %22CL1%22 and FILTER_NAME_2 == %22CL2%22')%0A    return clearnacs%0A%0A%0Adef filter_for_ringspan(clearnacs, spanlimit):%0A    %22filter for covered ringspan, giver in km.%22%0A    delta = clearnacs.MAXIMUM_RING_RADIUS - clearnacs.MINIMUM_RING_RADIUS%0A    f = delta %3C spanlimit%0A    ringspan = clearnacs%5Bf%5D.copy()%0A
     
@@ -1880,12 +1880,17 @@
 urn 
-df%0A#
+ringspan%0A
 %0A%0Acl

add get_clearnacs_ring_images and filter_for_ringspan