#
#------------------------------------------------------------------------------
# Copyright (c) 2013-2014, Christian Therien
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#------------------------------------------------------------------------------
#
# envi.py - This file is part of the PySptools package.
#

"""
load_ENVI_file, load_ENVI_spec_lib functions
"""


import os.path as osp
import numpy as np
import spectral.io.envi as envi


def load_ENVI_file(file_name):
    """
    Load the data, the wavelength vector and the wavelength units from an ENVI file.
    It use the SPy (spectral) library. At 'file_name' give the envi header file name.

    Parameters:
        file_name: `path string`
            The complete path to the file to load. Use the header file name.

    Returns: `tuple`
        data: `numpy array`
            A (m x n x p) HSI cube.

        info: `dictionary`
            * info['z plot titles'] : a list, first position is the x axis label,
              second position is the y axis label.
            * info['wavelength'] : a wavelengths list (1D python list).
            * info['wavelength units'] : the x axis units, 'Unknown' if not specified.
     """
    img = envi.open(file_name)
    head = envi.read_envi_header(file_name)
    # Because each ENVI header file is different and comes with
    # the inspiration of the moment, you need to fix the axis names
    # here.
    info = {}
    # Default
    info['z plot titles'] = ['Wavelength [um]', 'Reflectance']
    # Special cases
    if head['wavelength units'] == 'Nanometers':
        info['z plot titles'] = ['Wavelength [nm]', 'Reflectance']
    if head['wavelength units'] == 'Unknown':
        info['z plot titles'] = ['Unknown', 'Reflectance']
    if head['wavelength units'] == 'Wavenumber (cm-1)':
        info['z plot titles'] = head['z plot titles']

    # Default
    info['wavelength'] = [float(x) for x in head['wavelength']]
    info['wavelength units'] = head['wavelength units']
    return np.array(img.load()), info


def load_ENVI_spec_lib(file_name):
    """
    Load a ENVI .sli file.

    Parameters:
        file_name: `path string`
            The complete path to the library file to load.

    Returns: `numpy array`
        A (n x p) HSI cube.
    """
    sli = envi.open(file_name)
    head = envi.read_envi_header(file_name)
    info = {}
    info['wavelength'] = [float(x) for x in head['wavelength']]
    return sli.spectra, info
