%pip uninstall -yq earthaccess
%pip install -q git+https://github.com/nsidc/earthaccess.git@explore
import earthaccess
import ipyleaflet
from ipywidgets import Dropdown
from shapely.geometry.polygon import orient
from shapely.geometry import Polygon

auth = earthaccess.login()
# ArcticDEM
# note that we need to use the same projection for the image service layer and the map.
m1 = ipyleaflet.Map(
    center=(90, 0),
    zoom=4,
    basemap=ipyleaflet.basemaps.Esri.ArcticOceanBase,
    crs=ipyleaflet.projections.EPSG5936.ESRIBasemap,
)
# add arctic ocean reference basemap
tl1 = ipyleaflet.basemap_to_tiles(ipyleaflet.basemaps.Esri.ArcticOceanReference)
m1.add(tl1)

# create a widget control for the raster function
raster_functions = [
    "Aspect Map",
    "Contour 25",
    "Hillshade Elevation Tinted",
    "Hillshade Gray",
    "Height Ellipsoidal",
    "Height Orthometric",
    "Slope Map"]
raster_dropdown1 = Dropdown(
    value=raster_functions[3],
    options=raster_functions,
    description="Raster:",
)

# add image service layer with ArcticDEM
url = 'https://elevation2.arcgis.com/arcgis/rest/services/Polar/ArcticDEM/ImageServer'
rendering_rule = {"rasterFunction": raster_dropdown1.value}
image_layer = ipyleaflet.ImageService(
    name="CustomBaseLayer",
    url=url,
    format='jpgpng', rendering_rule=rendering_rule,
    attribution='Esri, PGC, UMN, NSF, NGA, DigitalGlobe',
    crs=ipyleaflet.projections.EPSG5936.ESRIBasemap)

m1.add(image_layer) 

# add control for raster function
dropdown_control = ipyleaflet.WidgetControl(widget=raster_dropdown1, position="topright")
m1.add(dropdown_control)

# set the rendering rule
def set_raster_function(sender):
    image_layer.rendering_rule = {"rasterFunction": raster_dropdown1.value}
    # force redrawing of map by removing and adding layer
    m1.remove(image_layer)
    m1.add(image_layer)


# watch raster function widget for changes
raster_dropdown1.observe(set_raster_function)
# polygon = [(-83.837578, 45.82529), (-80.167794, 45.82529), (-80.167794, 46.021921), (-83.837578, 46.021921), (-83.837578, 45.82529)]
coords = [(-139.59, 59.53), (-138.80, 59.90), (-137.15, 59.45),(-137.30, 58.78),(-138.64, 59.18),(-139.59, 59.53)]
polygon = list(orient(Polygon(coords)).exterior.coords)


if 'sw' in vars():
    if len(sw.roi) > 0:
        polygon = sw.roi
else:
    sw = earthaccess.SearchWidget(map=m1)


params = {
    "concept_id" : ["C2596864127-NSIDC_CPRD", "C2076090826-LPCLOUD", "C2237824918-ORNL_CLOUD"],
    "temporal": ("2020-01", "2023-09"),
    # "cloud_cover": (0, 20),
    "polygon": polygon
}
results = earthaccess.search_data(**params)
m = sw.explore(results, roi={"polygon": polygon})
# explore will inject its own controls so we add the base layer dropdown back
try:
    sw.map.add(dropdown_control)
except Exception:
    pass
m