# 
#  Copyright (C) 2012,2014,2016,2018  Smithsonian Astrophysical Observatory
#
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along
#  with this program; if not, write to the Free Software Foundation, Inc.,
#  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#


from pycrates import CrateSubspaceData
from pycrates.crateutils import convert_2_str
import pycrates.io as io
from collections import OrderedDict

class CrateSubspace:

    def __init__(self):
        self.__clear__()
        self.__ssdatalist = OrderedDict()


    def __clear__(self):
        self.name = ""
        if hasattr(self, "_CrateSubspace__ssdatalist"):
            self.__ssdatalist.clear()


    def __del__(self):
        self.__clear__()


    def __str__(self):
        return self.__repr__()


    def __repr__(self):
        retstr = ""
        for sskey in list(self.__ssdatalist.keys()):
            retstr += str(self.__ssdatalist[sskey]) + "\n"
        return retstr

        
    def add_subspace_data(self, data):
        """
        Appends input subspace data item to the subspace dictionary.
        """

        if isinstance(data, CrateSubspaceData):
            self.__ssdatalist[data.name] = data


    def get_subspace_datadict( self ):
        """
        Returns the dictionary of subspace data items.
        """
        return self.__ssdatalist


    def get_subspace_data( self, item ):
        """
        Retrieves the specified subspace data item (either a string or a number). 
        """
        if item is None: 
            return

        item = convert_2_str(item)
        
        item_str = None

        if isinstance(item, str):
            for name in list(self.__ssdatalist.keys()):
                if name.lower() == item.lower():
                    item_str = name
                    break

        elif isinstance(item, int):
            if item > 0 and item < (len(self.__ssdatalist)+1):
                for ii in range(1, (len(self.__ssdatalist)+1) ):
                    if ii == item:
                        item_str = (list(self.__ssdatalist.keys()))[ii-1]
                        break
        else:
            raise IndexError("Cannot find subspace item " + str(item) )

        return self.__ssdatalist[item_str]


    def get_subspace_ndata(self):
        """
        Returns the total number of data items in the subspace component.
        """
        return len(self.__ssdatalist.keys())
