# 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!')


import ee
import math
from cmt.mapclient_qt import addToMap
from cmt.util.miscUtilities import safe_get_info

def getCloudPercentage(lowResModis, region):
    '''Returns the percentage of a region flagged as clouds by the MODIS metadata'''

    MODIS_CLOUD_RESOLUTION = 1000 # Clouds are flagged at this resolution

    # Divide the number of cloud pixels by the total number of pixels
    oneMask    = ee.Image(1.0) 
    cloudMask  = getModisBadPixelMask(lowResModis)
    areaCount  = oneMask.reduceRegion(  ee.Reducer.sum(), region, MODIS_CLOUD_RESOLUTION)
    cloudCount = cloudMask.reduceRegion(ee.Reducer.sum(), region, MODIS_CLOUD_RESOLUTION)
    percentage = safe_get_info(cloudCount)['cloud_state'] / safe_get_info(areaCount)['constant']

    return percentage

def get_permanent_water_mask():
    return ee.Image("MODIS/MOD44W/MOD44W_005_2000_02_24").select(['water_mask'], ['b1'])



# If mixed_thresholds is true, we find the thresholds that contain 0.05 land and 0.95 water,
#  otherwise we find the threshold that most accurately splits the training data.
def compute_binary_threshold(valueImage, classification, bounds, mixed_thresholds=False):
    '''Computes a threshold for a value given examples in a classified binary image'''
    
    # Build histograms of the true and false labeled values
    valueInFalse   = valueImage.mask(classification.Not())
    valueInTrue    = valueImage.mask(classification)
    NUM_BINS       = 128
    SCALE          = 250 # In meters

# 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!')


# Path: cmt/modis/modis_utilities.py
import ee
import math
from cmt.mapclient_qt import addToMap
from cmt.util.miscUtilities import safe_get_info


def getCloudPercentage(lowResModis, region):
    '''Returns the percentage of a region flagged as clouds by the MODIS metadata'''

    MODIS_CLOUD_RESOLUTION = 1000 # Clouds are flagged at this resolution

    # Divide the number of cloud pixels by the total number of pixels
    oneMask    = ee.Image(1.0) 
    cloudMask  = getModisBadPixelMask(lowResModis)
    areaCount  = oneMask.reduceRegion(  ee.Reducer.sum(), region, MODIS_CLOUD_RESOLUTION)
    cloudCount = cloudMask.reduceRegion(ee.Reducer.sum(), region, MODIS_CLOUD_RESOLUTION)
    percentage = safe_get_info(cloudCount)['cloud_state'] / safe_get_info(areaCount)['constant']

    return percentage

def get_permanent_water_mask():
    return ee.Image("MODIS/MOD44W/MOD44W_005_2000_02_24").select(['water_mask'], ['b1'])



# If mixed_thresholds is true, we find the thresholds that contain 0.05 land and 0.95 water,
#  otherwise we find the threshold that most accurately splits the training data.
def compute_binary_threshold(valueImage, classification, bounds, mixed_thresholds=False):
    '''Computes a threshold for a value given examples in a classified binary image'''
    
    # Build histograms of the true and false labeled values
    valueInFalse   = valueImage.mask(classification.Not())
    valueInTrue    = valueImage.mask(classification)
    NUM_BINS       = 128
    SCALE          = 250 # In meters

    histogramFalse = safe_get_info(valueInFalse.reduceRegion(ee.Reducer.histogram(NUM_BINS, None, None), bounds, SCALE))['b1']