/*
 * Copyright 2016 Futurice GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

ext {
    // Freesound API
    freesound_api_client_id = getFreesoundApiClientId()
    freesound_api_client_secret = getFreesoundApiClientSecret()
    freesound_api_url = "\"https://www.freesound.org/apiv2/\""
}

String getFreesoundApiClientId() {
    return getProperty("freesound.api.clientId", "FREESOUND_API_CLIENT_ID")
}

String getFreesoundApiClientSecret() {
    return getProperty("freesound.api.clientSecret", "FREESOUND_API_CLIENT_SECRET")
}

String getProperty(String property, String envVariable) {
    String value = isCiBuild() ? fromEnv(envVariable) : fromFile(property);
    if (value == null || value.isEmpty()) {
        throw new IllegalStateException(
                "Could not find property: " + property + " value in property file or environment")
    }
    return "\"$value\""
}

private boolean isCiBuild() {
    fromEnv("TRAVIS") == "true"
}

private static fromEnv(String property) {
    System.getenv(property)
}

private String fromFile(String property) {
    Properties apiProperties = loadFileProperties("$projectDir/freesound-api.properties")
    return apiProperties.getProperty(property)
}

Properties loadFileProperties(String fileLocation) {
    Properties properties = new Properties()
    try {
        properties.load(new FileInputStream(fileLocation))
    } catch (FileNotFoundException fnf) {
        logger.log(LogLevel.ERROR,
                String.format("Missing Freesound API properties file: %s", fileLocation),
                fnf)
        throw fnf
    }
    return properties
}
