# 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
    return modis_utilities.apply_dem(domain, water_fraction)
   
#=====================================================================================

# This function is for testing modifications to the DNNS algorithm
def dnns_revised(domain, b):
    '''Dynamic Nearest Neighbor Search with revisions to improve performance on our test data'''
    
    # One issue with this algorithm is that its large search range slows down even Earth Engine!
    # - With a tiny kernel size, everything is relative to the region average which seems to work pretty well.
    # Another problem is that we don't have a good way of identifying 'Definately land' pixels like we do for water.
    
    # Parameters
    KERNEL_SIZE = 1 # The original paper used a 100x100 pixel box = 25,000 meters!
    PURELAND_THRESHOLD = 3500 # TODO: Vary by domain?
    PURE_WATER_THRESHOLD_RATIO = 0.1
    
    # Set up two square kernels of the same size
    # - These kernels define the search range for nearby pure water and land pixels
    kernel            = ee.Kernel.square(KERNEL_SIZE, 'pixels', False)
    kernel_normalized = ee.Kernel.square(KERNEL_SIZE, 'pixels', True)
    
    composite_image = b['b1'].addBands(b['b2']).addBands(b['b6'])
    
    # Compute (b2 - b1) < threshold, a simple water detection algorithm.  Treat the result as "pure water" pixels.
    pureWaterThreshold = float(domain.algorithm_params['modis_diff_threshold']) * PURE_WATER_THRESHOLD_RATIO
    pureWater = modis_diff(domain, b, pureWaterThreshold)
    
    # Compute the mean value of pure water pixels across the entire region, then store in a constant value image.
    AVERAGE_SCALE_METERS = 30 # This value seems to have no effect on the results

# 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

    return modis_utilities.apply_dem(domain, water_fraction)
   
#=====================================================================================

# This function is for testing modifications to the DNNS algorithm
def dnns_revised(domain, b):
    '''Dynamic Nearest Neighbor Search with revisions to improve performance on our test data'''
    
    # One issue with this algorithm is that its large search range slows down even Earth Engine!
    # - With a tiny kernel size, everything is relative to the region average which seems to work pretty well.
    # Another problem is that we don't have a good way of identifying 'Definately land' pixels like we do for water.
    
    # Parameters
    KERNEL_SIZE = 1 # The original paper used a 100x100 pixel box = 25,000 meters!
    PURELAND_THRESHOLD = 3500 # TODO: Vary by domain?
    PURE_WATER_THRESHOLD_RATIO = 0.1
    
    # Set up two square kernels of the same size
    # - These kernels define the search range for nearby pure water and land pixels
    kernel            = ee.Kernel.square(KERNEL_SIZE, 'pixels', False)
    kernel_normalized = ee.Kernel.square(KERNEL_SIZE, 'pixels', True)
    
    composite_image = b['b1'].addBands(b['b2']).addBands(b['b6'])
    
    # Compute (b2 - b1) < threshold, a simple water detection algorithm.  Treat the result as "pure water" pixels.
    pureWaterThreshold = float(domain.algorithm_params['modis_diff_threshold']) * PURE_WATER_THRESHOLD_RATIO
    pureWater = modis_diff(domain, b, pureWaterThreshold)
    
    # Compute the mean value of pure water pixels across the entire region, then store in a constant value image.
    AVERAGE_SCALE_METERS = 30 # This value seems to have no effect on the results

    averageWater      = safe_get_info(pureWater.mask(pureWater).multiply(composite_image).reduceRegion(ee.Reducer.mean(), domain.bounds, AVERAGE_SCALE_METERS))