/**
* Licensed Materials - Property of IBM* and/or HCL**
* IBM UrbanCode Deploy
* (c) Copyright IBM Corporation 2011, 2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*
* * Trademark of International Business Machines
* ** Trademark of HCL Technologies Limited
*/

package com.ibm.rational.air.plugin.worklight;

/**
* A utility class for helping to run the Worklight v8 REST API.
**/
public class V8Util {

    // All v8 endpoints begin with this path
    final String INIT_PATH = "/management-apis/2.0/runtimes"
    WLRestClient wlc

    public V8Util(String url, String user, String password) {
        this.wlc = new WLRestClient(URI.create(url), user, password)
    }

    /**
     * POST Path: https://www.example.com/mfpadmin/management-apis/2.0/runtimes/myruntime/adapters?async=false&locale=de_DE
     * param runtime The name of the runtime. This is the context root of the runtime web application, without the leading slash.
     * param adapterPath Path to the Adapter json file.
     * param async Whether the transaction is processed synchronously or asynchronously. The default mode is synchronous processing.
     * param locale The locale used for error messages.
     * return Create an IBM MobileFirst Adapter
     */
    public boolean postAdapter(String runtime, String adapterPath, String async, String locale) {
        boolean result = false
        String path = "${INIT_PATH}/${runtime}/adapters";
        path += addAsyncAndLocale(async, locale);

        int code = wlc.post(path, adapterPath);

        if (code >= 200 && code < 300) {
            println "Successfully deployed '${adapterPath}' adapter.";
            result = true
        } else {
            throw new RuntimeException("Failed to deploy '${adapterPath}' adapter.");
        }

        return result
    }

    /**
     * DELETE Path: https://www.example.com/mfpadmin/management-apis/2.0/runtimes/myruntime/adapters/myadapter?async=false&locale=de_DE
     * param runtime The name of the runtime. This is the context root of the runtime web application, without the leading slash.
     * param adapter Name of adapter to delete.
     * param async Whether the transaction is processed synchronously or asynchronously. The default mode is synchronous processing.
     * param locale The locale used for error messages.
     * return Delete an IBM MobileFirst Adapter
     */
    public boolean deleteAdapter(String runtime, String adapter, String async, String locale) {
        boolean result = false
        String path = "${INIT_PATH}/${runtime}/adapters/${adapter}";
        path += addAsyncAndLocale(async, locale);

        int code = wlc.delete(path);

        if (code >= 200 || code < 300) {
            println "Successfully deleted '${adapter}' adapter.";
            result = true
        } else {
            throw new RuntimeException("Failed to delete '${adapter}' adapter.");
        }

        return result
    }

    /**
     * POST Path: https://www.example.com/mfpadmin/management-apis/2.0/runtimes/myruntime/applications?async=false&locale=de_DE
     * param runtime The name of the runtime. This is the context root of the runtime web application, without the leading slash.
     * param applicationPath Path to the Application json file.
     * param async Whether the transaction is processed synchronously or asynchronously. The default mode is synchronous processing.
     * param locale The locale used for error messages.
     * return Create an IBM MobileFirst Application
     */
    public boolean postApplication(String runtime, String applicationPath, String async, String locale) {
        boolean result = false
        String path = "${INIT_PATH}/${runtime}/applications";
        path += addAsyncAndLocale(async, locale);

        int code = wlc.post(path, applicationPath);

        if (code >= 200 && code < 300) {
            println "Successfully deployed '${applicationPath}' application.";
            result = true
        } else {
            throw new RuntimeException("Failed to deploy '${applicationPath}' application.");
        }

        return result
    }

    /**
     * DELETE Path: https://www.example.com/mfpadmin/management-apis/2.0/runtimes/myruntime/applications/myapplication/android/1.0?async=false&locale=de_DE
     * param runtime The name of the runtime. This is the context root of the runtime web application, without the leading slash.
     * param application Name of the Application to delete.
     * param environment The application's environment.
     * param version The application's version.
     * param async Whether the transaction is processed synchronously or asynchronously. The default mode is synchronous processing.
     * param locale The locale used for error messages.
     * return Delete an IBM MobileFirst Application
     */
    public boolean deleteApplication(String runtime, String application, String environment, String version,
                    String async, String locale) {
        boolean result = false
        String path = "${INIT_PATH}/${runtime}/applications/${application}/${environment}/${version}";
        path += addAsyncAndLocale(async, locale);

        int code = wlc.delete(path);

        if (code >= 200 && code < 300) {
            println "Successfully deleted '${application}' application.";
            result = true
        } else {
            throw new RuntimeException("Failed to delete '${application}' application.");
        }

        return result
    }

    /**
     * PUT Path: https://www.example.com/mfpadmin/management-apis/2.0/runtimes/myruntime/applications/myapplication/android/1.0/config?async=false&locale=de_DE
     * param runtime The name of the runtime. This is the context root of the runtime web application, without the leading slash.
     * param application Name of application to reconfigure.
     * param environment The application's environment.
     * param version The application's version.
     * param async Whether the transaction is processed synchronously or asynchronously. The default mode is synchronous processing.
     * param locale The locale used for error messages.
     * return Sets the configuration of a specific application version.
     */
    public boolean putApplicationConfiguration(String runtime, String application, String environment,
                String version, String file, String async, String locale) {
        boolean result = false
        String path = "${INIT_PATH}/${runtime}/applications/${application}/${environment}/${version}/config";
        path += addAsyncAndLocale(async, locale);

        int code = wlc.put(path, file);

        if (code >= 200 && code < 300) {
            println "Successfully configured the '${application}' application.";
            result = true
        } else {
            throw new RuntimeException("Failed to configure '${application}' application.");
        }

        return result
    }

    public boolean postWebResource(String runtime, String application, String environment, String version,
                String archive) {
        return postWebResource(runtime, application, environment, version, archive, 'false', null)
    }

    /**
     * POST Path: https://www.example.dom/mfpadmin/management-apis/2.0/runtimes/myruntime/applications/myapplication/myapplicationenv/myapplicationversion/web?async=false&locale=de_DE
     * param runtime The name of the runtime. This is the context root of the runtime web application, without the leading slash.
     * param application The name of the application.
     * param environment The application environment.
     * param version The application version number.
     * param archive Path to the web resource zip file
     * param async Whether the transaction is processed synchronously or asynchronously. The default mode is synchronous processing.
     * param locale The locale used for error messages.
     * return Deploy a web resource zip for a specific application version
     */
    public boolean postWebResource(String runtime, String application, String environment, String version,
                String archive, String async, String locale) {
        boolean result = false
        String path = "${INIT_PATH}/${runtime}/applications/${application}/${environment}/${version}/web";
        path += addAsyncAndLocale(async, locale);

        int code = wlc.post(path, archive);

        if (code >= 200 && code < 300) {
            println "Successfully deployed '${archive}' web resource.";
            result = true
        } else {
            throw new RuntimeException("Failed to deploy '${archive}' web resource.");
        }

        return result
    }

    /**
     * Sample Query Path: ?async=false&locale=de_DE
     * param async Whether the transaction is processed synchronously or asynchronously. The default mode is synchronous processing.
     * param locale The locale used for error messages.
     * return Async and Locale query path to append to the URL.
     */
    private String addAsyncAndLocale(String async, String locale) {
        String result;
        if (async && locale) {
            result = "?async=${async}&locale=${locale}";
        } else if (async) {
            result = "?async=${async}";
        } else if (locale) {
            result = "?locale=${locale}";
        }
        return result;
    }
}
