# 
#  Copyright (C) 2016,2021  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.
#

"""
A collection of utility methods for general use in Crates module.
 + convert_2_str( <scalar string value> )

"""


__all__ = ['convert_2_str', 'parse_groupings']


def convert_2_str(input): 
    """
    Ensure provided string value is of the python 'str' type.

    The primary usage for this method is in the Python 2->3 conversion
    to handle string input arguments to methods.  Using this method
    allows the input to be either a bytes or unicode type string in 
    either case.  The result is always the native 'str' type:

       Python2.7   Python3.5
         str         bytes     1 byte per character..  utf-8
         unicode     str       4 bytes per character.. unicode

    Also accomodates numpy string array elements of type
       string_ , |S#, |U#

    NOTE: In any case, the expectation is that the input string
          contains only characters from the ASCII character set.

    Parameters
    ----------

      input  : string
                scalar string value to process.

    Returns
    --------
      result : str
                string value as 'str' type

    Raises
    --------
      none
    """
    output = input
    if "unicode" in str(type(input)):   #P2 unicode
        output = str(input)
    elif "bytes" in str(type(input)):   #P3 bytes
        output = input.decode("utf-8")
    elif "string_" in str(type(input)): #P2 numpy string_
        output = str(input)
    elif "str_" in str(type(input)):    #P3 numpy |U#
        output = str(input)
    
    return output


def parse_groupings(groupings):
    """
    A helper function for parsing and formating 'groupings' into a list of strings since 
    some routines have no access to cxcstdhdr lib.

    This is the same exact code as cxcstdhdr._is_valid().

    """

    # NOTE: If updating this code, cxcstdhdr._is_valid() should also have the same update.

    if groupings is None or (isinstance(groupings, (list,str)) and len(groupings) == 0):
        raise TypeError("Please specify header grouping(s).")
        
    if not isinstance(groupings, list):
        if isinstance(groupings, str):
            if ','  in groupings:                    
                groupings = groupings.split(",")
            else:
                groupings = [groupings]
        else:
            raise TypeError("Input groupings must be a string or list of strings.")

    # check if each item in list is a string
    if (all(isinstance(grp, str) for grp in groupings)) is False:
        raise TypeError("Input groupings must be a string or list of strings.")

    # convert input groupings to uppercase and remove any spaces from the group strings  
    groupings = [grp.replace(" ", "").upper() for grp in groupings]

    return groupings
