# Type 4 is TK - the mdis-nac is constant w.r.t. another frame
print(spice.frinfo(-236820))

# Verify that this is messenger
print(spice.bods2c('MESSENGER'))

# Load the ISIS Cube header
header = pvl.load('../../tests/data/EN1007907102M.cub')

isd['instrument_id'] = find_in_dict(header, 'InstrumentId')
isd['spacecraft_name'] = find_in_dict(header, 'SpacecraftName')
isd['target_name'] = find_in_dict(header, 'TargetName')

# Get the radii from SPICE
rad = spice.bodvrd(isd['target_name'], 'RADII', 3)
radii = rad[1]
isd['semi_major_axis'] = rad[1][0]
isd['semi_minor_axis'] = rad[1][1]


"""
Explanation: What is the minimum information needed to convert to and from the MDIS-NAC frame?
236: The code for the messenger spacecraft
4: Indicates that the frame is a TK Frame
236820: The code for the MDIS-NAC Frame
End of explanation
"""


# Here convert the sclock
sclock = find_in_dict(header, 'SpacecraftClockCount')
exposure_duration = find_in_dict(header, 'ExposureDuration')
exposure_duration = exposure_duration.value * 0.001  # Scale to seconds

# Get the instrument id, and, since this is a framer, set the time to the middle of the exposure
spacecraft_id = spice.bods2c('MESSENGER')
et = spice.scs2e(spacecraft_id, sclock)
print(et)
et += (exposure_duration / 2.0)

isd['ephemeris_time'] = et


# This needs to be sensor origin - like the comment below says...
# This is almost there - position w.r.t. the spacecraft, but not the camera yet.
loc, ltc = spice.spkpos('MESSENGER', isd['ephemeris_time'], 'IAU_MERCURY', 'NONE', isd['target_name'])
loc *= 1000
isd['x_sensor_origin'] = loc[0]
isd['y_sensor_origin'] = loc[1]
isd['z_sensor_origin'] = loc[2]

camera2bodyfixed = spice.pxform('MSGR_MDIS_NAC','IAU_MERCURY', isd['ephemeris_time'])
opk = spice.m2eul(camera2bodyfixed, 3, 2, 1)

isd['omega'] = opk[2]
isd['phi'] = opk[1]
isd['kappa'] = opk[0]

camera2bodyfixed

print(isd['omega'], isd['phi'], isd['kappa'])

class NumpyAwareJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.ndarray) and obj.ndim == 1:
            lobj = obj.tolist()
            if len(lobj) == 1:
                return lobj[0]
            else:
                return lobj
        return json.JSONEncoder.default(self, obj)

with open('isd.isd', 'w') as f:
    f.write(json.dumps(isd, f, cls=NumpyAwareJSONEncoder))

!cat isd.isd

# This is hard coded in Anne's script
isisFocalPlan2SocetPlate = np.eye(3)
isisFocalPlan2SocetPlate[1,1] = -1.0
isisFocalPlan2SocetPlate[2,2] = -1.0

# Grab the body fixed coordinates from SPICE

# The mercury Naif ID code is 199
nid = 199


# OPK
isd['x_sensor_origin'] = 
isd['y_sensor_origin'] = 
isd['z_sensor_origin'] = 
isd['omega'] = 
isd['phi'] =
isd['kappa'] = 

# ISD Search Information - totally fabricated.
isd['min_elevation'] = -1.0
isd['max_elevation'] = 1.0

isd

"""
Explanation: Now we need to compute time.
End of explanation
"""


