plugins {
  id "org.tenne.rest" version "0.4.2"
}

def makeAddDocTask = { doc, thenClosure={println it} ->
    def taskname = doc.hashCode()+"postRest"
    task "${taskname}"(type: org._10ne.gradle.rest.RestTask) {
        httpMethod = 'post'
        uri = 'http://localhost:5984/gradleoffilth/'
        //username = 'player'
        //password = 'password'
        requestBody = doc
        contentType = groovyx.net.http.ContentType.JSON
        requestHeaders = [customHeader: 'WoW']
        responseHandler = {
            thenClosure(it)
        }
    }
    return taskname
}

def makeDocFetchTask = { id, thenClosure={println it} ->
    def taskname = id.hashCode()+"getRest"
    task "${taskname}"(type: org._10ne.gradle.rest.RestTask) {
        httpMethod = 'get'
        uri = 'http://localhost:5984/gradleoffilth/test'
        //username = 'user'
        //password = 'password'
        contentType = groovyx.net.http.ContentType.JSON
        responseHandler = {
            thenClosure(it)
        }
    }
    return taskname
}

def makeDocUpdateTask = { id, updateClosure={it}, thenClosure={println it} ->
    def doc = []
    def fetchtaskname = makeDocFetchTask(id,{
            //project.tasks[fetchtaskname].ext.doc = it
            doc = it
        })
    def updatetaskname = id.hashCode()+"update"
    task "${updatetaskname}" {
        doLast {
            //def tmp = project.tasks[fetchtaskname].doc
            def tmp = doc
            println "before" + tmp
            tmp = updateClosure(tmp)
            println "after" + tmp
            //project.tasks[updatetaskname].ext.doc = tmp
            doc = tmp
        }
        dependsOn fetchtaskname
    }

    def taskname = id.hashCode()+"putRest"
    task "${taskname}"(type: org._10ne.gradle.rest.RestTask) {
        println "will push " doc
        httpMethod = 'put'
        uri = 'http://localhost:5984/gradleoffilth/test'
        //username = 'player'
        //password = 'password'
        requestBody = doc    //"${ project.tasks[updatetaskname].ext.doc }"
        contentType = groovyx.net.http.ContentType.JSON
        requestHeaders = [customHeader: 'WoW']
        responseHandler = {
            thenClosure(it)
        }
    }
    project.tasks[taskname].dependsOn(updatetaskname)
    return taskname
}

def newDoc = makeAddDocTask([_id : 'test' ])
def getDoc = makeDocFetchTask('test')
project.tasks[getDoc].dependsOn(newDoc)
def updateDoc = makeDocUpdateTask('test',{
    it._delete=true
    it
})
project.tasks[updateDoc].dependsOn(getDoc)
task main
main.dependsOn(newDoc)
main.dependsOn(getDoc)
main.dependsOn(updateDoc)
