"""
Utility function for assign_wcs.

"""
import logging
import functools
import numpy as np

from astropy.coordinates import SkyCoord
from astropy.utils.misc import isiterable
from astropy.io import fits
from astropy.modeling import models as astmodels
from astropy.table import QTable
from astropy.constants import c
from typing import Union, List

from gwcs import WCS
from gwcs.wcstools import wcs_from_fiducial, grid_from_bounding_box
from gwcs import utils as gwutils
from stdatamodels import DataModel

from . import pointing
from ..lib.catalog_utils import SkyObject
from ..transforms.models import GrismObject
from ..datamodels import WavelengthrangeModel


log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)


__all__ = ["reproject", "wcs_from_footprints", "velocity_correction",
           "MSAFileError", "NoDataOnDetectorError", "compute_scale",
           "calc_rotation_matrix"]


class MSAFileError(Exception):

    def __init__(self, message):
        super(MSAFileError, self).__init__(message)


class NoDataOnDetectorError(Exception):
    """WCS solution indicates no data on detector

    When WCS solutions are available, the solutions indicate that no data
    will be present, raise this exception.

    Specific example is for NIRSpec and the NRS2 detector. For various
    configurations of the MSA, it is possible that no dispersed spectra will
    appear on NRS2. This is not a failure of calibration, but needs to be
    called out in order for the calling architecture to be aware of this.

    """

    def __init__(self, message=None):
        if message is None:
            message = 'WCS solution indicate that no science is in the data.'
        super(NoDataOnDetectorError, self).__init__(message)


def _domain_to_bounding_box(domain):
    # TODO: remove this when domain is completely removed
    bb = tuple([(item['lower'], item['upper']) for item in domain])
    if len(bb) == 1:
        bb = bb[0]
    return bb


def reproject(wcs1, wcs2):
    """
    Given two WCSs return a function which takes pixel coordinates in
    the first WCS and computes their location in the second one.

    It performs the forward transformation of ``wcs1`` followed by the
    inverse of ``wcs2``.

    Parameters
    ----------
    wcs1, wcs2 : `~gwcs.wcs.WCS`
        WCS objects.

    Returns
    -------
    _reproject : func
        Function to compute the transformations.  It takes x, y
        positions in ``wcs1`` and returns x, y positions in ``wcs2``.
    """

    def _reproject(x, y):
        sky = wcs1.forward_transform(x, y)
        return wcs2.backward_transform(*sky)
    return _reproject


def compute_scale(wcs: WCS, fiducial: Union[tuple, np.ndarray],
                  disp_axis: int = None, pscale_ratio: float = None) -> float:
    """Compute scaling transform.

    Parameters
    ----------
    wcs : `~gwcs.wcs.WCS`
        Reference WCS object from which to compute a scaling factor.

    fiducial : tuple
        Input fiducial of (RA, DEC) or (RA, DEC, Wavelength) used in calculating reference points.

    disp_axis : int
        Dispersion axis integer. Assumes the same convention as `wcsinfo.dispersion_direction`

    pscale_ratio : int
        Ratio of input to output pixel scale

    Returns
    -------
    scale : float
        Scaling factor for x and y or cross-dispersion direction.

    """
    spectral = 'SPECTRAL' in wcs.output_frame.axes_type

    if spectral and disp_axis is None:
        raise ValueError('If input WCS is spectral, a disp_axis must be given')

    crpix = np.array(wcs.invert(*fiducial))

    delta = np.zeros_like(crpix)
    spatial_idx = np.where(np.array(wcs.output_frame.axes_type) == 'SPATIAL')[0]
    delta[spatial_idx[0]] = 1

    crpix_with_offsets = np.vstack((crpix, crpix + delta, crpix + np.roll(delta, 1))).T
    crval_with_offsets = wcs(*crpix_with_offsets)

    coords = SkyCoord(ra=crval_with_offsets[spatial_idx[0]], dec=crval_with_offsets[spatial_idx[1]], unit="deg")
    xscale = np.abs(coords[0].separation(coords[1]).value)
    yscale = np.abs(coords[0].separation(coords[2]).value)

    if pscale_ratio is not None:
        xscale = xscale * pscale_ratio
        yscale = yscale * pscale_ratio

    if spectral:
        # Assuming scale doesn't change with wavelength
        # Assuming disp_axis is consistent with DataModel.meta.wcsinfo.dispersion.direction
        return yscale if disp_axis == 1 else xscale

    return np.sqrt(xscale * yscale)


def calc_rotation_matrix(roll_ref: float, v3i_yang: float, vparity: int = 1) -> List[float]:
    """Calculate the rotation matrix.

    Parameters
    ----------
    roll_ref : float
        Telescope roll angle of V3 North over East at the ref. point in radians

    v3i_yang : float
        The angle between ideal Y-axis and V3 in radians.

    vparity : int
        The x-axis parity, usually taken from the JWST SIAF parameter VIdlParity.
        Value should be "1" or "-1".

    Returns
    -------
    matrix: [pc1_1, pc1_2, pc2_1, pc2_2]
        The rotation matrix

    Notes
    -----
    The rotation is

       ----------------
       | pc1_1  pc2_1 |
       | pc1_2  pc2_2 |
       ----------------

    """
    if vparity not in (1, -1):
        raise ValueError(f'vparity should be 1 or -1. Input was: {vparity}')

    rel_angle = roll_ref - (vparity * v3i_yang)

    pc1_1 = vparity * np.cos(rel_angle)
    pc1_2 = np.sin(rel_angle)
    pc2_1 = vparity * -np.sin(rel_angle)
    pc2_2 = np.cos(rel_angle)

    return [pc1_1, pc1_2, pc2_1, pc2_2]


def wcs_from_footprints(dmodels, refmodel=None, transform=None, bounding_box=None,
                        pscale_ratio=None):
    """
    Create a WCS from a list of input data models.

    A fiducial point in the output coordinate frame is created from  the
    footprints of all WCS objects. For a spatial frame this is the center
    of the union of the footprints. For a spectral frame the fiducial is in
    the beginning of the footprint range.
    If ``refmodel`` is None, the first WCS object in the list is considered
    a reference. The output coordinate frame and projection (for celestial frames)
    is taken from ``refmodel``.
    If ``transform`` is not suplied, a compound transform is created using
    CDELTs and PC.
    If ``bounding_box`` is not supplied, the bounding_box of the new WCS is computed
    from bounding_box of all input WCSs.

    Parameters
    ----------
    dmodels : list of `~jwst.datamodels.DataModel`
        A list of data models.
    refmodel : `~jwst.datamodels.DataModel`, optional
        This model's WCS is used as a reference.
        WCS. The output coordinate frame, the projection and a
        scaling and rotation transform is created from it. If not supplied
        the first model in the list is used as ``refmodel``.
    transform : `~astropy.modeling.core.Model`, optional
        A transform, passed to :meth:`~gwcs.wcstools.wcs_from_fiducial`
        If not supplied Scaling | Rotation is computed from ``refmodel``.
    bounding_box : tuple, optional
        Bounding_box of the new WCS.
        If not supplied it is computed from the bounding_box of all inputs.
    pscale_ratio : float, optional
        Ratio of input to output pixel scale.
    """
    bb = bounding_box
    wcslist = [im.meta.wcs for im in dmodels]

    if not isiterable(wcslist):
        raise ValueError("Expected 'wcslist' to be an iterable of WCS objects.")

    if not all([isinstance(w, WCS) for w in wcslist]):
        raise TypeError("All items in wcslist are to be instances of gwcs.WCS.")

    if refmodel is None:
        refmodel = dmodels[0]
    else:
        if not isinstance(refmodel, DataModel):
            raise TypeError("Expected refmodel to be an instance of DataModel.")

    fiducial = compute_fiducial(wcslist, bb)
    ref_fiducial = compute_fiducial([refmodel.meta.wcs])

    prj = astmodels.Pix2Sky_TAN()


    if transform is None:
        transform = []
        wcsinfo = pointing.wcsinfo_from_model(refmodel)
        sky_axes, spec, other = gwutils.get_axes(wcsinfo)

        # Need to put the rotation matrix (List[float, float, float, float])
        # returned from calc_rotation_matrix into the correct shape for
        # constructing the transformation
        roll_ref = np.deg2rad(refmodel.meta.wcsinfo.roll_ref)
        v3yangle = np.deg2rad(refmodel.meta.wcsinfo.v3yangle)
        vparity = refmodel.meta.wcsinfo.vparity
        pc = np.reshape(
            calc_rotation_matrix(roll_ref, v3yangle, vparity=vparity),
            (2, 2)
        )

        rotation = astmodels.AffineTransformation2D(pc)
        transform.append(rotation)

        if sky_axes:
            scale = compute_scale(refmodel.meta.wcs, ref_fiducial,
                                  pscale_ratio=pscale_ratio)
            transform.append(astmodels.Scale(scale) & astmodels.Scale(scale))

        if transform:
            transform = functools.reduce(lambda x, y: x | y, transform)

    out_frame = refmodel.meta.wcs.output_frame
    input_frame = dmodels[0].meta.wcs.input_frame
    wnew = wcs_from_fiducial(fiducial, coordinate_frame=out_frame, projection=prj,
                             transform=transform, input_frame=input_frame)

    footprints = [w.footprint().T for w in wcslist]
    domain_bounds = np.hstack([wnew.backward_transform(*f) for f in footprints])

    for axs in domain_bounds:
        axs -= (axs.min()  + .5)

    output_bounding_box = []
    for axis in out_frame.axes_order:
        axis_min, axis_max = domain_bounds[axis].min(), domain_bounds[axis].max()
        output_bounding_box.append((axis_min, axis_max))

    output_bounding_box = tuple(output_bounding_box)
    ax1, ax2 = np.array(output_bounding_box)[sky_axes]
    offset1 = (ax1[1] - ax1[0]) / 2
    offset2 = (ax2[1] - ax2[0]) / 2
    offsets = astmodels.Shift(-offset1) & astmodels.Shift(-offset2)

    wnew.insert_transform('detector', offsets, after=True)
    wnew.bounding_box = output_bounding_box

    return wnew


def compute_fiducial(wcslist, bounding_box=None):
    """
    For a celestial footprint this is the center.
    For a spectral footprint, it is the beginning of the range.

    This function assumes all WCSs have the same output coordinate frame.
    """

    axes_types = wcslist[0].output_frame.axes_type
    spatial_axes = np.array(axes_types) == 'SPATIAL'
    spectral_axes = np.array(axes_types) == 'SPECTRAL'
    footprints = np.hstack([w.footprint(bounding_box=bounding_box).T for w in wcslist])
    spatial_footprint = footprints[spatial_axes]
    spectral_footprint = footprints[spectral_axes]

    fiducial = np.empty(len(axes_types))
    if spatial_footprint.any():
        lon, lat = spatial_footprint
        lon, lat = np.deg2rad(lon), np.deg2rad(lat)
        x_mean = np.mean(np.cos(lat) * np.cos(lon))
        y_mean = np.mean(np.cos(lat) * np.sin(lon))
        z_mean = np.mean(np.sin(lat))
        lon_fiducial = np.rad2deg(np.arctan2(y_mean, x_mean)) % 360.0
        lat_fiducial = np.rad2deg(np.arctan2(z_mean, np.sqrt(x_mean ** 2 + y_mean ** 2)))
        fiducial[spatial_axes] = lon_fiducial, lat_fiducial
    if spectral_footprint.any():
        fiducial[spectral_axes] = spectral_footprint.min()
    return fiducial


def is_fits(input_img):
    """
    Returns
    --------
    isFits: tuple
        An ``(isfits, fitstype)`` tuple.  The values of ``isfits`` and
        ``fitstype`` are specified as:

         - ``isfits``: True|False
         - ``fitstype``: if True, one of 'waiver', 'mef', 'simple'; if False, None

    Notes
    -----
    Input images which do not have a valid FITS filename will automatically
    result in a return of (False, None).

    In the case that the input has a valid FITS filename but runs into some
    error upon opening, this routine will raise that exception for the calling
    routine/user to handle.
    """

    isfits = False
    fitstype = None
    names = ['fits', 'fit', 'FITS', 'FIT']
    # determine if input is a fits file based on extension
    # Only check type of FITS file if filename ends in valid FITS string
    f = None
    fileclose = False
    if isinstance(input_img, fits.HDUList):
        isfits = True
        f = input_img
    else:
        isfits = True in [input_img.endswith(l) for l in names]

    # if input is a fits file determine what kind of fits it is
    # waiver fits len(shape) == 3
    if isfits:
        if not f:
            try:
                f = fits.open(input_img, mode='readonly')
                fileclose = True
            except Exception:
                if f is not None:
                    f.close()
                raise
        data0 = f[0].data
        if data0 is not None:
            try:
                if isinstance(f[1], fits.TableHDU):
                    fitstype = 'waiver'
            except IndexError:
                fitstype = 'simple'

        else:
            fitstype = 'mef'
        if fileclose:
            f.close()

    return isfits, fitstype


def subarray_transform(input_model):
    """
    Return an offset model if the observation uses a subarray.

    Parameters
    ----------
    input_model : `~jwst.datamodels.DataModel`
        Data model.

    Returns
    -------
    subarray2full : `~astropy.modeling.core.Model` or ``None``
        Returns a (combination of ) ``Shift`` models if a subarray is used.
        Returns ``None`` if a full frame observation.
    """
    tr_xstart = astmodels.Identity(1)
    tr_ystart = astmodels.Identity(1)

    # These quanities are 1-based
    xstart = input_model.meta.subarray.xstart
    ystart = input_model.meta.subarray.ystart

    if xstart is not None and xstart != 1:
        tr_xstart = astmodels.Shift(xstart -1)

    if ystart is not None and ystart != 1:
        tr_ystart = astmodels.Shift(ystart -1)

    if (isinstance(tr_xstart, astmodels.Identity) and
        isinstance(tr_ystart, astmodels.Identity)):
        # the case of a full frame observation
        return None
    else:
        subarray2full = tr_xstart & tr_ystart
        return subarray2full


def not_implemented_mode(input_model, ref, slit_y_range=None):
    """
    Return ``None`` if assign_wcs has not been implemented for a mode.
    """
    exp_type = input_model.meta.exposure.type
    message = "WCS for EXP_TYPE of {0} is not implemented.".format(exp_type)
    log.critical(message)
    return None


def get_object_info(catalog_name=None):
    """Return a list of SkyObjects from the direct image

    The source_catalog step catalog items are read into a list
    of  SkyObjects which can be referenced by catalog id. Only
    the columns needed by the WFSS code are saved.

    Parameters
    ----------
    catalog_name : str, astropy.table.table.Qtable
        The name of the photutils catalog or its quantities table

    Returns
    -------
    objects : list[jwst.transforms.models.SkyObject]
        A list of SkyObject tuples

    Notes
    -----

    """
    if isinstance(catalog_name, str):
        if len(catalog_name) == 0:
            err_text = "Empty catalog filename"
            log.error(err_text)
            raise ValueError(err_text)
        try:
            catalog = QTable.read(catalog_name, format='ascii.ecsv')
        except FileNotFoundError as e:
            log.error("Could not find catalog file: {0}".format(e))
            raise FileNotFoundError("Could not find catalog: {0}".format(e))
    elif isinstance(catalog_name, QTable):
        catalog = catalog_name
    else:
        err_text = "Need to input string name of catalog or astropy.table.table.QTable instance"
        log.error(err_text)
        raise TypeError(err_text)

    objects = []

    # validate that the expected columns are there
    required_fields = set(SkyObject()._fields)

    try:
        if not set(required_fields).issubset(set(catalog.colnames)):
            difference = set(required_fields).difference(set(catalog.colnames))
            err_text = "Missing required columns in source catalog: {0}".format(difference)
            log.error(err_text)
            raise KeyError(err_text)
    except AttributeError as e:
        err_text = "Problem validating object catalog columns: {0}".format(e)
        log.error(err_text)
        raise AttributeError

    # The columns are named sky_bbox_ll, sky_bbox_ul, sky_bbox_lr,
    # and sky_bbox_ur, each of which is a SkyCoord (i.e. RA & Dec & frame) at
    # one corner of the minimal bounding box. There will also be a sky_bbox
    # property as a 4-tuple of SkyCoord, but that is not serializable
    # (hence, the four separate columns).

    for row in catalog:
        objects.append(SkyObject(id=row['id'],
                                 xcentroid=row['xcentroid'],
                                 ycentroid=row['ycentroid'],
                                 sky_centroid=row['sky_centroid'],
                                 isophotal_abmag=row['isophotal_abmag'],
                                 isophotal_abmag_err=row['isophotal_abmag_err'],
                                 sky_bbox_ll=row['sky_bbox_ll'],
                                 sky_bbox_lr=row['sky_bbox_lr'],
                                 sky_bbox_ul=row['sky_bbox_ul'],
                                 sky_bbox_ur=row['sky_bbox_ur'],
                                 is_star=row['is_star']
                                 )
                       )
    return objects


def create_grism_bbox(input_model,
                      reference_files=None,
                      mmag_extract=99.0,
                      extract_orders=None,
                      wfss_extract_half_height=None,
                      wavelength_range=None):
    """Create bounding boxes for each object in the catalog

    The sky coordinates in the catalog image are first related
    to the grism image. They need to go through the WCS object
    in order to find the "direct image" pixel location, which is
    also in a detector pixel coordinate frame. This "direct image"
    location can then be sent through the trace polynomials to find
    the spectral location on the grism image for that wavelength and order.


    Parameters
    ----------
    input_model : `jwst.datamodels.ImagingModel`
        Data model which holds the grism image
    reference_files : dict, optional
        Dictionary of reference file names.
        If ``None``, ``wavelength_range`` must be supplied to specify
        the orders and corresponding wavelength ranges to be used in extraction.
    mmag_extract : float, optional
        The faintest magnitude to extract from the catalog.
    extract_orders : list, optional
        The list of orders to extract, if specified this will
        override the orders listed in the wavelengthrange reference file.
        If ``None``, the default one in the wavelengthrange reference file is used.
    wfss_extract_half_height : int, optional
        Cross-dispersion extraction half height in pixels, WFSS mode.
        Overwrites the computed extraction height in ``GrismObject.order_bounding.``
        If ``None``, it's computed from the segementation map,
        using the min and max wavelength for each of the orders that
        are available.
    wavelength_range : dict, optional
        Pairs of {spectral_order: (wave_min, wave_max)} for each order.
        If ``None``, the default one in the wavelengthrange reference file is used.

    Returns
    -------
    grism_objects : list
        A list of GrismObject(s) for every source in the catalog.
        Each grism object contains information about its
        spectral extent.

    Notes
    -----
    The wavelengthrange reference file is used to govern
    the extent of the bounding box for each object. The name of the
    catalog has been stored in the input models meta information under
    the source_catalog key.

    It's left to the calling routine to cut the bounding boxes at the
    extent of the detector (for example, extract 2d would only extract
    the on-detector portion of the bounding box)

    Bounding box dispersion direction is dependent on the filter and
    module for NIRCAM and changes for GRISMR, but is consistent for GRISMC,
    see https://jwst-docs.stsci.edu/display/JTI/NIRCam+Wide+Field+Slitless+Spectroscopy

    NIRISS has one detector.  GRISMC disperses along rows and
    GRISMR disperses along columns.

    If ``wfss_extract_half_height`` is specified it is used to compute the extent in
    the cross-dispersion direction, which becomes ``2 * wfss_extract_half_height + 1``.
    ``wfss_extract_half_height`` can only be applied to point source objects.

    """
    instr_name = input_model.meta.instrument.name
    if instr_name == "NIRCAM":
        filter_name = input_model.meta.instrument.filter
    elif instr_name == "NIRISS":
        filter_name = input_model.meta.instrument.pupil
    else:
        raise ValueError("create_grism_object works with NIRCAM and NIRISS WFSS exposures only.")

    if reference_files is None:
        # Get the list of extract_orders and lmin, lmax from wavelength_range.
        if wavelength_range is None:
            message = "If reference files are not supplied, ``wavelength_range`` must be provided."
            raise TypeError(message)
    else:
        # Get the list of extract_orders and lmin, lmax from the ``wavelengthrange`` reference file.
        with WavelengthrangeModel(reference_files['wavelengthrange']) as f:
            if 'WFSS' not in f.meta.exposure.type:
                err_text = "Wavelengthrange reference file not for WFSS"
                log.error(err_text)
                raise ValueError(err_text)
            ref_extract_orders = f.extract_orders
            if extract_orders is None:
                #ref_extract_orders = extract_orders
                extract_orders = [x[1] for x in ref_extract_orders if x[0] == filter_name].pop()

            wavelength_range = f.get_wfss_wavelength_range(filter_name, extract_orders)


    if not isinstance(mmag_extract, (int, float)):
        raise TypeError(f"Expected mmag_extract to be a number, got {mmag_extract}")
    log.info("Extracting objects < abmag = {0}".format(mmag_extract))

    # extract the catalog objects
    if input_model.meta.source_catalog is None:
        err_text = "No source catalog listed in datamodel."
        log.error(err_text)
        raise ValueError(err_text)

    log.info(f"Getting objects from {input_model.meta.source_catalog}")

    return _create_grism_bbox(input_model, mmag_extract, wfss_extract_half_height, wavelength_range)


def _create_grism_bbox(input_model, mmag_extract=99.0,
                       wfss_extract_half_height=None, wavelength_range=None):

    log.debug(f'Extracting with wavelength_range {wavelength_range}')

    # this contains the pure information from the catalog with no translations
    skyobject_list = get_object_info(input_model.meta.source_catalog)
    # get the imaging transform to record the center of the object in the image
    # here, image is in the imaging reference frame, before going through the
    # dispersion coefficients

    sky_to_detector = input_model.meta.wcs.get_transform('world', 'detector')
    sky_to_grism = input_model.meta.wcs.backward_transform

    grism_objects = []  # the return list of GrismObjects
    for obj in skyobject_list:
        if obj.isophotal_abmag is not None:
            if obj.isophotal_abmag < mmag_extract:
                # could add logic to ignore object if too far off image,

                # save the image frame center of the object
                # takes in ra, dec, wavelength, order but wave and order
                # don't get used until the detector->grism_detector transform
                xcenter, ycenter, _, _ = sky_to_detector(obj.sky_centroid.icrs.ra.value,
                                                         obj.sky_centroid.icrs.dec.value,
                                                         1, 1)

                order_bounding = {}
                waverange = {}
                partial_order = {}
                for order in wavelength_range:
                    # range_select = [(x[2], x[3]) for x in wavelengthrange if (x[0] == order and x[1] == filter_name)]
                    # The orders of the bounding box in the non-dispersed image
                    # drive the extraction extent. The location of the min and
                    # max wavelengths for each order are used to get the
                    # location of the +/- sides of the bounding box in the
                    # grism image
                    lmin, lmax = wavelength_range[order]
                    ra = np.array([obj.sky_bbox_ll.ra.value, obj.sky_bbox_lr.ra.value,
                                   obj.sky_bbox_ul.ra.value, obj.sky_bbox_ur.ra.value])
                    dec = np.array([obj.sky_bbox_ll.dec.value, obj.sky_bbox_lr.dec.value,
                                   obj.sky_bbox_ul.dec.value, obj.sky_bbox_ur.dec.value])
                    x1, y1, _, _, _ = sky_to_grism(ra, dec, [lmin] * 4, [order]*4)
                    x2, y2, _, _, _ = sky_to_grism(ra, dec, [lmax] * 4, [order]*4)

                    xstack = np.hstack([x1, x2])
                    ystack = np.hstack([y1, y2])

                    # Subarrays are only allowed in nircam tsgrism mode. The polynomial transforms
                    # only work with the full frame coordinates. The code here is called during extract_2d,
                    # and is creating bounding boxes which should be in the full frame coordinates, it just
                    # uses the input catalog and the magnitude to limit the objects that need bounding boxes.

                    # Tsgrism is always supposed to have the source object at the same pixel, and that is
                    # hardcoded into the transforms. At least a while ago, the 2d extraction for tsgrism mode
                    # didn't call this bounding box code. So I think it's safe to leave the subarray
                    # subtraction out, i.e. do not subtract x/ystart.

                    xmin = int(np.min(xstack))
                    xmax = int(np.max(xstack))
                    ymin = int(np.min(ystack))
                    ymax = int(np.max(ystack))

                    if wfss_extract_half_height is not None and obj.is_star:
                        if input_model.meta.wcsinfo.dispersion_direction == 2:
                            center = (xmax + xmin) / 2
                            xmin = center - wfss_extract_half_height
                            xmax = center + wfss_extract_half_height
                        elif input_model.meta.wcsinfo.dispersion_direction == 1:
                            center = (ymax + ymin) / 2
                            ymin = center - wfss_extract_half_height
                            ymax = center + wfss_extract_half_height
                        else:
                            raise ValueError("Cannot determine dispersion direction.")

                    # don't add objects and orders which are entirely
                    # off the detector partial_order marks partial
                    # off-detector objects which are near enough to
                    # cause spectra to be observed on the detector.
                    # This is usefull because the catalog often is
                    # created from a resampled direct image that is
                    # bigger than the detector FOV for a single grism
                    # exposure.
                    exclude = False
                    ispartial = False

                    pts = np.array([[ymin, xmin], [ymax, xmax]])
                    ll = np.array([0, 0])
                    ur = np.array([input_model.meta.subarray.ysize, input_model.meta.subarray.xsize])
                    inidx = np.all(np.logical_and(ll <= pts, pts <= ur), axis=1)
                    contained = len(pts[inidx])

                    if contained == 0:
                        exclude = True
                        log.info("Excluding off-image object: {}, order {}".format(obj.id, order))
                    elif contained >= 1:
                        outbox = pts[np.logical_not(inidx)]
                        if len(outbox) > 0:
                            ispartial = True
                            log.info("Partial order on detector for obj: {} order: {}".format(obj.id, order))

                    if not exclude:
                        order_bounding[order] = ((round(ymin), round(ymax)), (round(xmin), round(xmax)))
                        waverange[order] = ((lmin, lmax))
                        partial_order[order] = ispartial

                if len(order_bounding) > 0:
                    grism_objects.append(GrismObject(sid=obj.id,
                                                     order_bounding=order_bounding,
                                                     sky_centroid=obj.sky_centroid,
                                                     partial_order=partial_order,
                                                     waverange=waverange,
                                                     sky_bbox_ll=obj.sky_bbox_ll,
                                                     sky_bbox_lr=obj.sky_bbox_lr,
                                                     sky_bbox_ul=obj.sky_bbox_ul,
                                                     sky_bbox_ur=obj.sky_bbox_ur,
                                                     xcentroid=xcenter,
                                                     ycentroid=ycenter))
    if len(grism_objects) == 0:
        log.warning("No grism objects saved, check catalog")
    return grism_objects


def get_num_msa_open_shutters(shutter_state):
    """
    Return the number of open shutters in a slitlet.

    Parameters
    ----------
    shutter_state : str
        ``Slit.shutter_state`` attribute - a combination of
        ``1`` - open shutter, ``0`` - closed shutter, ``x`` - main shutter.
    """
    num = shutter_state.count('1')
    if 'x' in shutter_state:
        num += 1
    return num


def transform_bbox_from_shape(shape):
    """Create a bounding box from the shape of the data.

    This is appropriate to attached to a transform.

    Parameters
    ----------
    shape : tuple
        The shape attribute from a `numpy.ndarray` array

    Returns
    -------
    bbox : tuple
        Bounding box in y, x order.
    """
    bbox = ((-0.5, shape[-2] - 0.5),
            (-0.5, shape[-1] - 0.5))
    return bbox


def wcs_bbox_from_shape(shape):
    """Create a bounding box from the shape of the data.

    This is appropriate to attach to a wcs object
    Parameters
    ----------
    shape : tuple
        The shape attribute from a `numpy.ndarray` array

    Returns
    -------
    bbox : tuple
        Bounding box in x, y order.
    """
    bbox = ((-0.5, shape[-1] - 0.5),
            (-0.5, shape[-2] - 0.5))
    return bbox


def bounding_box_from_subarray(input_model):
    """Create a bounding box from the subarray size.

    Note: The bounding_box assumes full frame coordinates.
    It is set to ((ystart, ystart + xsize), (xstart, xstart + xsize)).
    It is in 0-based coordinates.

    Parameters
    ----------
    input_model : `~jwst.datamodels.DataModel`
        The data model.

    Returns
    -------
    bbox : tuple
        Bounding box in y, x order.
    """
    bb_xstart = -0.5
    bb_xend = -0.5
    bb_ystart = -0.5
    bb_yend = -0.5

    if input_model.meta.subarray.xsize is not None:
        bb_xend = input_model.meta.subarray.xsize - 0.5
    if input_model.meta.subarray.ysize is not None:
        bb_yend = input_model.meta.subarray.ysize - 0.5

    bbox = ((bb_ystart, bb_yend), (bb_xstart, bb_xend))
    return bbox


def update_s_region_imaging(model):
    """
    Update the ``S_REGION`` keyword using ``WCS.footprint``.
    """

    bbox = model.meta.wcs.bounding_box

    if bbox is None:
        bbox = wcs_bbox_from_shape(model.data.shape)

    # footprint is an array of shape (2, 4) as we
    # are interested only in the footprint on the sky
    footprint = model.meta.wcs.footprint(bbox, center=True, axis_type="spatial").T
    # take only imaging footprint
    footprint = footprint[:2, :]

    # Make sure RA values are all positive
    negative_ind = footprint[0] < 0
    if negative_ind.any():
        footprint[0][negative_ind] = 360 + footprint[0][negative_ind]

    footprint = footprint.T
    update_s_region_keyword(model, footprint)


def compute_footprint_spectral(model):
    """
    Determine spatial footprint for spectral observations using the instrument model.

    Parameters
    ----------
    model : `~jwst.datamodels.IFUImageModel`
        The output of assign_wcs.
    """
    swcs = model.meta.wcs
    bbox = swcs.bounding_box
    if bbox is None:
        bbox = wcs_bbox_from_shape(model.data.shape)

    x, y = grid_from_bounding_box(bbox)
    ra, dec, lam = swcs(x, y)
    footprint = np.array([[np.nanmin(ra), np.nanmin(dec)],
                          [np.nanmax(ra), np.nanmin(dec)],
                          [np.nanmax(ra), np.nanmax(dec)],
                          [np.nanmin(ra), np.nanmax(dec)]])
    return footprint


def update_s_region_spectral(model):
    """ Update the S_REGION keyword.
    """
    footprint = compute_footprint_spectral(model)
    update_s_region_keyword(model, footprint)


def compute_footprint_nrs_slit(slit):
    """ Compute the footprint of a Nirspec slit using the instrument model.

    Parameters
    ----------
    slit : `~jwst.datamodels.SlitModel`
    """
    slit2world = slit.meta.wcs.get_transform("slit_frame", "world")
    # Define the corners of a virtual slit. The center of the slit is (0, 0).
    virtual_corners_x = [-.5, -.5, .5, .5]
    virtual_corners_y = [slit.slit_ymin, slit.slit_ymax, slit.slit_ymax, slit.slit_ymin]
    # Use a default wavelength or 2 microns as input to the transform.
    input_lam = [2e-6] * 4
    ra, dec, lam = slit2world(virtual_corners_x,
                              virtual_corners_y,
                              input_lam)
    return np.array([ra, dec]).T


def update_s_region_nrs_slit(slit):
    footprint = compute_footprint_nrs_slit(slit)
    update_s_region_keyword(slit, footprint)


def update_s_region_keyword(model, footprint):
    """ Update the S_REGION keyword.
    """
    s_region = (
        "POLYGON ICRS "
        " {0:.9f} {1:.9f}"
        " {2:.9f} {3:.9f}"
        " {4:.9f} {5:.9f}"
        " {6:.9f} {7:.9f}".format(*footprint.flatten()))
    if "nan" in s_region:
        # do not update s_region if there are NaNs.
        log.info("There are NaNs in s_region, S_REGION not updated.")
    else:
        model.meta.wcsinfo.s_region = s_region
        log.info("Update S_REGION to {}".format(model.meta.wcsinfo.s_region))


def _nanminmax(wcsobj):
    x, y = grid_from_bounding_box(wcsobj.bounding_box)
    ra, dec, lam = wcsobj(x, y)
    return np.nanmin(ra), np.nanmax(ra), np.nanmin(dec), np.nanmax(dec)


def compute_footprint_nrs_ifu(output_model, mod):
    """
    determine NIRSPEC ifu footprint observations using the instrument model.

    Parameters
    ----------
    output_model : `~jwst.datamodels.IFUImageModel`
        The output of assign_wcs.
    mod : module
        The imported ``nirspec`` module.
    """
    wcs_list = mod.nrs_ifu_wcs(output_model)
    ra_total = []
    dec_total = []
    for wcsobj in wcs_list:
        rmin, rmax, dmin, dmax = _nanminmax(wcsobj)
        ra_total.append((rmin, rmax))
        dec_total.append((dmin, dmax))
    ra_max = np.asarray(ra_total)[:, 1].max()
    ra_min = np.asarray(ra_total)[:, 0].min()
    dec_max = np.asarray(dec_total)[:, 1].max()
    dec_min = np.asarray(dec_total)[:, 0].min()
    footprint = np.array([ra_min, dec_min, ra_max, dec_min, ra_max, dec_max, ra_min, dec_max])
    return footprint


def update_s_region_nrs_ifu(output_model, mod):
    """
    Update S_REGION for NRS_IFU observations using calculated footprint.

    Parameters
    ----------
    output_model : `~jwst.datamodels.IFUImageModel`
        The output of assign_wcs.
    mod : module
        The imported ``nirspec`` module.
    """
    footprint = compute_footprint_nrs_ifu(output_model, mod)
    update_s_region_keyword(output_model, footprint)


def update_s_region_mrs(output_model):
    """
    Update S_REGION for MIRI_MRS observations using the WCS transforms.

    Parameters
    ----------
    output_model : `~jwst.datamodels.IFUImageModel`
        The output of assign_wcs.
    """
    footprint = compute_footprint_spectral(output_model)
    update_s_region_keyword(output_model, footprint)


def velocity_correction(velosys):
    """
    Compute wavelength correction to Barycentric reference frame.

    Parameters
    ----------
    velosys : float
        Radial velocity wrt Barycenter [m / s].
    """
    correction = (1 / (1 + velosys / c.value))
    model = astmodels.Identity(1) * astmodels.Const1D(correction, name="velocity_correction")
    model.inverse = astmodels.Identity(1) / astmodels.Const1D(correction, name="inv_vel_correciton")

    return model
