"""
ROIs seen by MAJIS during GCO5000
=================================

Example of opportunities for MAJIS to observe
Ganymede ROIs during GCO5000 phase.

"""

import matplotlib.pyplot as plt

from planetary_coverage import GANYMEDE, GanymedeROIs, TourConfig, read_events
from planetary_coverage.misc import wget
from planetary_coverage.ticks import deg_ticks


# %%
# Download JUICE mission phases from the SOC
# ------------------------------------------

# %%
URL = 'https://juicesoc.esac.esa.int/data/DATA/crema_5_0'
MISSION_PHASES = 'Mission_Phases.csv'

wget(f'{URL}/{MISSION_PHASES}', MISSION_PHASES, skip=True)

# %%
# Get GCO 5000 windows from the mission phases
# --------------------------------------------

# %%
phases = read_events(MISSION_PHASES)

gco_5000 = phases['GCO5000']

gco_5000

# %%
# Load JUICE trajectory during GCO 5000
# -------------------------------------

# %%
tour = TourConfig(mk='5.1 150lb', spacecraft='JUICE', instrument='MAJIS',
                  target='Ganymede', version='v400')

majis_gco_5000 = tour[gco_5000:'15 min']

majis_gco_5000

# %%
# Keep only the part of the trajectory well lighted
# -------------------------------------------------

# %%
traj = majis_gco_5000.where(majis_gco_5000.inc < 70)

traj

# %%
# Find the ROIs intersected by the trajectory
# -------------------------------------------

# %%
traj_in_rois = traj & GanymedeROIs

traj_in_rois

# %%
rois_visible = GanymedeROIs & traj
rois_not_visible = GanymedeROIs ^ traj

len(GanymedeROIs), len(rois_visible), len(rois_not_visible)

# %%
(
    f'{len(rois_visible) / len(GanymedeROIs):.0%} of Ganymede ROIs are '
    'visible with MAJIS with an incidence lower than 70° during GCO 5000.'
)

# %%
# Represent the intersection opportunities on the map
# ---------------------------------------------------

# %%
fig = plt.figure(figsize=(12, 9))
ax = fig.add_subplot(projection=GANYMEDE)

ax.add_collection(traj_in_rois.fovs(facecolors='inc', vmin=45, vmax=70, sort='inc'))

ax.add_collection(rois_visible(edgecolors='red'))
ax.add_collection(rois_not_visible(edgecolors='white', linewidths=1, linestyles='--'))

ax.colorbar(vmin=45, vmax=70, label='inc')
ax.twin_colorbar(label='Solar elevation', format=90 - deg_ticks)
ax.set_title('MAJIS coverage opportunities during GCO 5000 (downlink windows excluded)')

plt.show()


# %%
# .. admonition:: Download
#
#   - :download:`majis_gco_5000.ipynb`
#   - :download:`majis_gco_5000.py`
