"""Read the NOAA/Metop AVHRR relative spectral response functions.

Data from NOAA STAR:
https://www.star.nesdis.noaa.gov/smcd/spb/fwu/homepage/AVHRR/spec_resp_func/index.html
"""

import logging
import os

import numpy as np

from pyspectral.raw_reader import InstrumentRSR
from pyspectral.utils import INSTRUMENTS
from pyspectral.utils import convert2hdf5 as tohdf5

LOG = logging.getLogger(__name__)

AVHRR_BAND_NAMES = {'avhrr/3': ['ch1', 'ch2', 'ch3a', 'ch3b', 'ch4', 'ch5'],
                    'avhrr/2': ['ch1', 'ch2', 'ch3', 'ch4', 'ch5'],
                    'avhrr/1': ['ch1', 'ch2', 'ch3', 'ch4']}


class AvhrrRSR(InstrumentRSR):
    """Container for the NOAA/Metop AVHRR RSR data."""

    def __init__(self, bandname, platform_name):
        """Initialize the class."""
        super(AvhrrRSR, self).__init__(
            bandname, platform_name,
            AVHRR_BAND_NAMES[INSTRUMENTS[platform_name]])

        self.instrument = INSTRUMENTS.get(platform_name, 'avhrr/3')

        self._get_options_from_config()
        self._get_bandfilenames()

        LOG.debug("Filenames: %s", str(self.filenames))
        if self.filenames[bandname] and os.path.exists(self.filenames[bandname]):
            self.requested_band_filename = self.filenames[bandname]
            if self.instrument == 'avhrr/1':
                self._load(scale=0.001)
            else:
                self._load()

        else:
            LOG.warning("Couldn't find an existing file for this band: %s",
                        str(self.bandname))

        # To be compatible with VIIRS....
        self.filename = self.requested_band_filename

    def _load(self, scale=1.0):
        """Load the AVHRR RSR data for the band requested."""
        data = np.genfromtxt(self.requested_band_filename,
                             unpack=True,
                             names=['wavelength',
                                    'response'],
                             skip_header=1)

        wavelength = data['wavelength'] * scale
        response = data['response']

        self.rsr = {'wavelength': wavelength, 'response': response}


if __name__ == "__main__":
    for platform_name in ["Metop-C", ]:
        instrument = INSTRUMENTS.get(platform_name)
        if instrument:
            tohdf5(AvhrrRSR, platform_name, AVHRR_BAND_NAMES.get(instrument))
