// Documentation: https://api-testing.onehippo.io/v3/docs
@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1')
@Grab(group='org.apache.httpcomponents', module='httpclient', version='4.5')
@Grab(value = 'org.apache.httpcomponents:httpmime:4.5')


import groovy.json.JsonBuilder
import groovy.transform.Field;
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.ContentType
import groovyx.net.http.Method
import org.apache.http.entity.mime.MultipartEntity
import org.apache.http.entity.mime.HttpMultipartMode
import org.apache.http.entity.mime.content.FileBody
import org.apache.http.entity.mime.content.StringBody

@Field def doDebug = false


@Field String apiBase = "https://api-testing.onehippo.io"
String usersURL = "${apiBase}/v3/users/"
String login = "${apiBase}/v3/authn/access_token"

//String username = ""
//String password = ""

String newUser = ""
String newEmail = ""
String newPassword = ""
String newRole = "user"
String newProject = "testing"

username = System.console().readLine 'Admin username: '
password = System.console().readLine 'Admin password: '


def access_token = doLogin(login, username, password);
// json property token_type:bearer, use this to make token logic more generic
String token = "Bearer " + access_token


def users = doListUsers(usersURL, token)
users.each() { user ->
    println "${user.username} (${user.email}) active:${user.active} role:${user.role}" //username, active, email, role, status
}

println "\nCreate new user"
newUsername = System.console().readLine 'username: '
newEmail = System.console().readLine 'email: '
newPassword = System.console().readLine 'password: '

println addUser(usersURL, newUsername, newEmail, newPassword, newRole, newProject, token)

//deleteUser("${usersURL}/p.gupta@onehippo.com", token)

def doLogin(def URL, def username, String password) {
    def jsonBuilder = new groovy.json.JsonBuilder();
    jsonBuilder  'username': username, 'password': password

    return executeJsonCall(URL, Method.POST, null, jsonBuilder).access_token
}

def doListUsers(def URL, def token) {
println URL
println token
    return executeJsonCall(URL, Method.GET, token)
}

def addUser(String URL, String username, String email, String password, String role, String project, String token) {
    def jsonBuilder = new groovy.json.JsonBuilder();
    jsonBuilder  'username': username, 'email': email, 'role': role, 'project': project, 'password': password
    println jsonBuilder.toString()
    return executeJsonCall(URL, Method.POST, token, jsonBuilder)
}


def deleteUser(def URL, def token) {
    return executeJsonCall(URL, Method.DELETE, token)
}

def debug(def msg) {
    if(doDebug) {
        println msg
    }
}

def executeJsonCall(String APIPath, Method method, String token, JsonBuilder jsonBuilder = null) {
    debug jsonBuilder
    debug APIPath
    def http = new HTTPBuilder( APIPath )
    http.ignoreSSLIssues()
    http.request( method, ContentType.JSON ) { req ->
        if(token != null){
            headers.'Authorization' = token
        }

        if(jsonBuilder != null) {
            body = jsonBuilder.toString()
            headers.'Content-Type' = "application/json"
            headers.'Accept: application/vnd.onehippo.api+json;version=3'
        }
        response.success = { resp, json ->
            debug "Response: ${resp.status} with json ${json}"
            return json
        }
        response.failure = { resp, json ->
            debug "Request failed with status ${resp.status}; json: ${json}"
            throw new Exception("${json.error}")
        }
    }
}
