# Path: cmt/mapclient_qt.py
# def addToMap(self, eeobject, vis_params=None, name="", show=True):
#     '''Ads an EE object to the map'''
#         
#     # Flatten any lists to comma separated strings - needed for eeobject.getMapId() call below!
#     if vis_params:
#         vis_params = dict(vis_params)
#         for key in vis_params.keys():
#             item = vis_params.get(key)
#             if (isinstance(item, collections.Iterable) and (not isinstance(item, basestring))):
#                  vis_params[key] = ','.join([str(x) for x in item])
# 
#     def execute_thread(waiting_threads):
#         # get thread before starting
#         with self.thread_lock:
#             pass
#         result = eeobject.getMapId(vis_params)
#         for t in waiting_threads:
#             t.join()
#         with self.thread_lock:
#             self.executing_threads.pop(0)
#         return result
# 
#     with self.thread_lock:
#         self.executing_threads.append(cmt.util.miscUtilities.waitForEeResult(functools.partial(execute_thread, list(self.executing_threads)),
#                     lambda a : self.addOverlay(MakeTileManager(a), eeobject, name, show, vis_params)))
# 
# Path: cmt/util/miscUtilities.py
# def safe_get_info(ee_object, max_num_attempts=5):
#     '''Keep trying to call getInfo() on an Earth Engine object until it succeeds.'''
#     
#     # Do not try again if we get one of these exceptions
#     fail_messages = ['Too many pixels']
#     
#     num_attempts = 0
#     while True:
#         try:
#             return ee_object.getInfo()
#         except Exception as e:
#             # Rethrow the exception if it is not timeout related
#             for message in fail_messages:
#                 if message in str(e):
#                     raise e
#                     
#             print('Earth Engine Error: %s. Waiting 10s and then retrying.' % (e))
#             time.sleep(10)
#             num_attempts += 1
#         if max_num_attempts and (num_attempts >= max_num_attempts):
#             raise Exception('safe_get_info failed to succeed after ' +str(num_attempts)+ ' attempts!')
# 
# def get_permanent_water_mask():
#     '''Returns the global permanent water mask'''
#     return ee.Image("MODIS/MOD44W/MOD44W_005_2000_02_24").select(['water_mask'], ['b1'])


import ee
import math
import modis_utilities
import ee_classifiers
import simple_modis_algorithms
from cmt.mapclient_qt import addToMap
from cmt.util.miscUtilities import safe_get_info, get_permanent_water_mask

    # Implement equations 10 and 11 from the paper
    oneOverSix   = b['b1'].divide(b['b6'])
    twoOverSix   = b['b2'].divide(b['b6'])
    eqTenLeft    = oneOverSix.subtract( averageWaterLocal.select('sur_refl_b01').divide(b['b6']) )
    eqElevenLeft = twoOverSix.subtract( averageWaterLocal.select('sur_refl_b02').divide(b['b6']) )
    
    # For each pixel, grab all the ratios from nearby pixels
    nearbyPixelsOneOverSix = oneOverSix.neighborhoodToBands(kernel) # Each of these images has one band per nearby pixel
    nearbyPixelsTwoOverSix = twoOverSix.neighborhoodToBands(kernel)
    nearbyPixelsOne        = b['b1'].neighborhoodToBands(kernel)
    nearbyPixelsTwo        = b['b2'].neighborhoodToBands(kernel)
    nearbyPixelsSix        = b['b6'].neighborhoodToBands(kernel)
    
    # Find which nearby pixels meet the EQ 10 and 11 criteria
    eqTenMatches        = ( nearbyPixelsOneOverSix.gt(eqTenLeft   ) ).And( nearbyPixelsOneOverSix.lt(oneOverSix) )
    eqElevenMatches     = ( nearbyPixelsTwoOverSix.gt(eqElevenLeft) ).And( nearbyPixelsTwoOverSix.lt(twoOverSix) )
    nearbyLandPixels    = eqTenMatches.And(eqElevenMatches)
    
    # Find the average of the nearby matching pixels
    numNearbyLandPixels = nearbyLandPixels.reduce(ee.Reducer.sum())
    meanNearbyBandOne   = nearbyPixelsOne.multiply(nearbyLandPixels).reduce(ee.Reducer.sum()).divide(numNearbyLandPixels)
    meanNearbyBandTwo   = nearbyPixelsTwo.multiply(nearbyLandPixels).reduce(ee.Reducer.sum()).divide(numNearbyLandPixels)
    meanNearbyBandSix   = nearbyPixelsSix.multiply(nearbyLandPixels).reduce(ee.Reducer.sum()).divide(numNearbyLandPixels)


    # Pack the results into a three channel image for the whole region
    meanNearbyLand = meanNearbyBandOne.addBands(meanNearbyBandTwo).addBands(meanNearbyBandSix)
    meanNearbyLand = meanNearbyLand.multiply(numNearbyLandPixels.gte(MIN_PURE_NEARBY)).add( averagePureLandImage.multiply(numNearbyLandPixels.lt(MIN_PURE_NEARBY)) )


# Path: cmt/mapclient_qt.py
# def addToMap(self, eeobject, vis_params=None, name="", show=True):
#     '''Ads an EE object to the map'''
#         
#     # Flatten any lists to comma separated strings - needed for eeobject.getMapId() call below!
#     if vis_params:
#         vis_params = dict(vis_params)
#         for key in vis_params.keys():
#             item = vis_params.get(key)
#             if (isinstance(item, collections.Iterable) and (not isinstance(item, basestring))):
#                  vis_params[key] = ','.join([str(x) for x in item])
# 
#     def execute_thread(waiting_threads):
#         # get thread before starting
#         with self.thread_lock:
#             pass
#         result = eeobject.getMapId(vis_params)
#         for t in waiting_threads:
#             t.join()
#         with self.thread_lock:
#             self.executing_threads.pop(0)
#         return result
# 
#     with self.thread_lock:
#         self.executing_threads.append(cmt.util.miscUtilities.waitForEeResult(functools.partial(execute_thread, list(self.executing_threads)),
#                     lambda a : self.addOverlay(MakeTileManager(a), eeobject, name, show, vis_params)))
# 
# Path: cmt/util/miscUtilities.py
# def safe_get_info(ee_object, max_num_attempts=5):
#     '''Keep trying to call getInfo() on an Earth Engine object until it succeeds.'''
#     
#     # Do not try again if we get one of these exceptions
#     fail_messages = ['Too many pixels']
#     
#     num_attempts = 0
#     while True:
#         try:
#             return ee_object.getInfo()
#         except Exception as e:
#             # Rethrow the exception if it is not timeout related
#             for message in fail_messages:
#                 if message in str(e):
#                     raise e
#                     
#             print('Earth Engine Error: %s. Waiting 10s and then retrying.' % (e))
#             time.sleep(10)
#             num_attempts += 1
#         if max_num_attempts and (num_attempts >= max_num_attempts):
#             raise Exception('safe_get_info failed to succeed after ' +str(num_attempts)+ ' attempts!')
# 
# def get_permanent_water_mask():
#     '''Returns the global permanent water mask'''
#     return ee.Image("MODIS/MOD44W/MOD44W_005_2000_02_24").select(['water_mask'], ['b1'])


# Path: cmt/modis/dnns.py
import ee
import math
import modis_utilities
import ee_classifiers
import simple_modis_algorithms
from cmt.mapclient_qt import addToMap
from cmt.util.miscUtilities import safe_get_info, get_permanent_water_mask


    # Implement equations 10 and 11 from the paper
    oneOverSix   = b['b1'].divide(b['b6'])
    twoOverSix   = b['b2'].divide(b['b6'])
    eqTenLeft    = oneOverSix.subtract( averageWaterLocal.select('sur_refl_b01').divide(b['b6']) )
    eqElevenLeft = twoOverSix.subtract( averageWaterLocal.select('sur_refl_b02').divide(b['b6']) )
    
    # For each pixel, grab all the ratios from nearby pixels
    nearbyPixelsOneOverSix = oneOverSix.neighborhoodToBands(kernel) # Each of these images has one band per nearby pixel
    nearbyPixelsTwoOverSix = twoOverSix.neighborhoodToBands(kernel)
    nearbyPixelsOne        = b['b1'].neighborhoodToBands(kernel)
    nearbyPixelsTwo        = b['b2'].neighborhoodToBands(kernel)
    nearbyPixelsSix        = b['b6'].neighborhoodToBands(kernel)
    
    # Find which nearby pixels meet the EQ 10 and 11 criteria
    eqTenMatches        = ( nearbyPixelsOneOverSix.gt(eqTenLeft   ) ).And( nearbyPixelsOneOverSix.lt(oneOverSix) )
    eqElevenMatches     = ( nearbyPixelsTwoOverSix.gt(eqElevenLeft) ).And( nearbyPixelsTwoOverSix.lt(twoOverSix) )
    nearbyLandPixels    = eqTenMatches.And(eqElevenMatches)
    
    # Find the average of the nearby matching pixels
    numNearbyLandPixels = nearbyLandPixels.reduce(ee.Reducer.sum())
    meanNearbyBandOne   = nearbyPixelsOne.multiply(nearbyLandPixels).reduce(ee.Reducer.sum()).divide(numNearbyLandPixels)
    meanNearbyBandTwo   = nearbyPixelsTwo.multiply(nearbyLandPixels).reduce(ee.Reducer.sum()).divide(numNearbyLandPixels)
    meanNearbyBandSix   = nearbyPixelsSix.multiply(nearbyLandPixels).reduce(ee.Reducer.sum()).divide(numNearbyLandPixels)


    # Pack the results into a three channel image for the whole region
    meanNearbyLand = meanNearbyBandOne.addBands(meanNearbyBandTwo).addBands(meanNearbyBandSix)
    meanNearbyLand = meanNearbyLand.multiply(numNearbyLandPixels.gte(MIN_PURE_NEARBY)).add( averagePureLandImage.multiply(numNearbyLandPixels.lt(MIN_PURE_NEARBY)) )


    addToMap(numNearbyLandPixels,  {'min': 0, 'max': 400, }, 'numNearbyLandPixels', False)