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()

[((13, 19, 13, 31), 'threading.Semaphore', 'Semaphore', ({(13, 29, 13, 30): '5'}, {}), '(5)', False, 'from threading import Semaphore\n'), ((14, 21, 14, 33), 'threading.Semaphore', 'Semaphore', ({(14, 31, 14, 32): '2'}, {}), '(2)', False, 'from threading import Semaphore\n'), ((22, 13, 22, 50), 'google.auth.crypt.RSASigner.from_string', 'crypt.RSASigner.from_string', ({(22, 41, 22, 49): 'key_data'}, {}), '(key_data)', False, 'from google.auth import crypt\n'), ((23, 34, 28, 5), 'google.oauth2.service_account.Credentials', 'service_account.Credentials', (), '', False, 'from google.oauth2 import service_account\n'), ((38, 4, 38, 36), 'ee.InitializeThread', 'ee.InitializeThread', ({(38, 24, 38, 35): 'credentials'}, {}), '(credentials)', False, 'import ee\n'), ((42, 18, 42, 41), 'ee.data.getAssetRoots', 'ee.data.getAssetRoots', ({}, {}), '()', False, 'import ee\n'), ((49, 4, 49, 52), 'logging.info', 'logging.info', ({(49, 17, 49, 51): "('Recursively deleting ' + asset_id)"}, {}), "('Recursively deleting ' + asset_id)", False, 'import logging\n'), ((50, 7, 50, 32), 'ee.data.getInfo', 'ee.data.getInfo', ({(50, 23, 50, 31): 'asset_id'}, {}), '(asset_id)', False, 'import ee\n'), ((64, 4, 68, 5), 'ee.data.create_assets', 'ee.data.create_assets', (), '', False, 'import ee\n'), ((72, 4, 76, 5), 'ee.data.create_assets', 'ee.data.create_assets', (), '', False, 'import ee\n'), ((34, 15, 34, 56), 'json.loads', 'json.loads', ({(34, 26, 34, 55): "request.headers['sepal-user']"}, {}), "(request.headers['sepal-user'])", False, 'import json\n'), ((51, 17, 54, 10), 'ee.data.getList', 'ee.data.getList', ({(51, 33, 54, 9): "{'id': asset_id, 'fields': 'id'}"}, {}), "({'id': asset_id, 'fields': 'id'})", False, 'import ee\n'), ((58, 8, 58, 37), 'ee.data.deleteAsset', 'ee.data.deleteAsset', ({(58, 28, 58, 36): 'asset_id'}, {}), '(asset_id)', False, 'import ee\n'), ((59, 8, 59, 43), 'logging.info', 'logging.info', ({(59, 21, 59, 42): "('Deleted ' + asset_id)"}, {}), "('Deleted ' + asset_id)", False, 'import logging\n'), ((37, 26, 37, 66), 'google.oauth2.credentials.Credentials', 'Credentials', ({(37, 38, 37, 65): "googleTokens['accessToken']"}, {}), "(googleTokens['accessToken'])", False, 'from google.oauth2.credentials import Credentials\n'), ((56, 12, 56, 44), 'ee.data.deleteAsset', 'ee.data.deleteAsset', ({(56, 32, 56, 43): "image['id']"}, {}), "(image['id'])", False, 'import ee\n'), ((57, 12, 57, 50), 'logging.info', 'logging.info', ({(57, 25, 57, 49): "('Deleted ' + image['id'])"}, {}), "('Deleted ' + image['id'])", False, 'import logging\n')]