import json
from threading import Semaphore

import ee
from flask import request
from google.auth import crypt
from google.oauth2 import service_account
from google.oauth2.credentials import Credentials

service_account_credentials = None
import logging

export_semaphore = Semaphore(5)
get_info_semaphore = Semaphore(2)


def init_service_account_credentials(args):
    global service_account_credentials

    with open(args['gee_key_path'], 'r') as file_:
        key_data = file_.read()
    signer = crypt.RSASigner.from_string(key_data)
    service_account_credentials = service_account.Credentials(
        signer=signer,
        service_account_email=args['gee_email'],
        token_uri=ee.oauth.TOKEN_URI,
        scopes=ee.oauth.SCOPES + ['https://www.googleapis.com/auth/drive']
    )


def init_ee():
    credentials = service_account_credentials
    if 'sepal-user' in request.headers:
        user = json.loads(request.headers['sepal-user'])
        googleTokens = user.get('googleTokens', None)
        if googleTokens:
            credentials = Credentials(googleTokens['accessToken'])
    ee.InitializeThread(credentials)


def to_asset_id(asset_path):
    asset_roots = ee.data.getAssetRoots()
    if not asset_roots:
        raise Exception('User has no GEE asset roots')
    return asset_roots[0]['id'] + '/' + asset_path


def delete_asset_collection(asset_id):
    logging.info('Recursively deleting ' + asset_id)
    if ee.data.getInfo(asset_id):
        images = ee.data.getList({
            'id': asset_id,
            'fields': 'id'
        })
        for image in images:
            ee.data.deleteAsset(image['id'])
            logging.info('Deleted ' + image['id'])
        ee.data.deleteAsset(asset_id)
        logging.info('Deleted ' + asset_id)


def create_asset_image_collection(asset_id):
    delete_asset_collection(asset_id)
    ee.data.create_assets(
        asset_ids=[asset_id],
        asset_type=ee.data.ASSET_TYPE_IMAGE_COLL,
        mk_parents=True
    )


def create_asset_folder(asset_id):
    ee.data.create_assets(
        asset_ids=[asset_id],
        asset_type=ee.data.ASSET_TYPE_FOLDER,
        mk_parents=True
    )


def get_info(ee_object):
    try:
        get_info_semaphore.acquire()
        return ee_object.getInfo()
    finally:
        get_info_semaphore.release()

[((274, 286), 'threading.Semaphore', 'Semaphore', (['(5)'], {}), '(5)\n', (283, 286), False, 'from threading import Semaphore\n'), ((308, 320), 'threading.Semaphore', 'Semaphore', (['(2)'], {}), '(2)\n', (317, 320), False, 'from threading import Semaphore\n'), ((503, 540), 'google.auth.crypt.RSASigner.from_string', 'crypt.RSASigner.from_string', (['key_data'], {}), '(key_data)\n', (530, 540), False, 'from google.auth import crypt\n'), ((575, 766), 'google.oauth2.service_account.Credentials', 'service_account.Credentials', ([], {'signer': 'signer', 'service_account_email': "args['gee_email']", 'token_uri': 'ee.oauth.TOKEN_URI', 'scopes': "(ee.oauth.SCOPES + ['https://www.googleapis.com/auth/drive'])"}), "(signer=signer, service_account_email=args[\n    'gee_email'], token_uri=ee.oauth.TOKEN_URI, scopes=ee.oauth.SCOPES + [\n    'https://www.googleapis.com/auth/drive'])\n", (602, 766), False, 'from google.oauth2 import service_account\n'), ((1105, 1137), 'ee.InitializeThread', 'ee.InitializeThread', (['credentials'], {}), '(credentials)\n', (1124, 1137), False, 'import ee\n'), ((1187, 1210), 'ee.data.getAssetRoots', 'ee.data.getAssetRoots', ([], {}), '()\n', (1208, 1210), False, 'import ee\n'), ((1386, 1434), 'logging.info', 'logging.info', (["('Recursively deleting ' + asset_id)"], {}), "('Recursively deleting ' + asset_id)\n", (1398, 1434), False, 'import logging\n'), ((1442, 1467), 'ee.data.getInfo', 'ee.data.getInfo', (['asset_id'], {}), '(asset_id)\n', (1457, 1467), False, 'import ee\n'), ((1866, 1973), 'ee.data.create_assets', 'ee.data.create_assets', ([], {'asset_ids': '[asset_id]', 'asset_type': 'ee.data.ASSET_TYPE_IMAGE_COLL', 'mk_parents': '(True)'}), '(asset_ids=[asset_id], asset_type=ee.data.\n    ASSET_TYPE_IMAGE_COLL, mk_parents=True)\n', (1887, 1973), False, 'import ee\n'), ((2040, 2143), 'ee.data.create_assets', 'ee.data.create_assets', ([], {'asset_ids': '[asset_id]', 'asset_type': 'ee.data.ASSET_TYPE_FOLDER', 'mk_parents': '(True)'}), '(asset_ids=[asset_id], asset_type=ee.data.\n    ASSET_TYPE_FOLDER, mk_parents=True)\n', (2061, 2143), False, 'import ee\n'), ((913, 954), 'json.loads', 'json.loads', (["request.headers['sepal-user']"], {}), "(request.headers['sepal-user'])\n", (923, 954), False, 'import json\n'), ((1486, 1535), 'ee.data.getList', 'ee.data.getList', (["{'id': asset_id, 'fields': 'id'}"], {}), "({'id': asset_id, 'fields': 'id'})\n", (1501, 1535), False, 'import ee\n'), ((1703, 1732), 'ee.data.deleteAsset', 'ee.data.deleteAsset', (['asset_id'], {}), '(asset_id)\n', (1722, 1732), False, 'import ee\n'), ((1741, 1776), 'logging.info', 'logging.info', (["('Deleted ' + asset_id)"], {}), "('Deleted ' + asset_id)\n", (1753, 1776), False, 'import logging\n'), ((1060, 1100), 'google.oauth2.credentials.Credentials', 'Credentials', (["googleTokens['accessToken']"], {}), "(googleTokens['accessToken'])\n", (1071, 1100), False, 'from google.oauth2.credentials import Credentials\n'), ((1611, 1643), 'ee.data.deleteAsset', 'ee.data.deleteAsset', (["image['id']"], {}), "(image['id'])\n", (1630, 1643), False, 'import ee\n'), ((1656, 1694), 'logging.info', 'logging.info', (["('Deleted ' + image['id'])"], {}), "('Deleted ' + image['id'])\n", (1668, 1694), False, 'import logging\n')]