/*
 * Copyright 2018 the original author or authors.
 *
 * 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.
 */

import javax.inject.Inject
// tag::unit-of-work[]
// The parameters for a single unit of work
interface ReverseParameters extends WorkParameters {
    Property<File> getFileToReverse()
    Property<File> getDestinationFile()
}

// The implementation of a single unit of work. 
abstract class ReverseFile implements WorkAction<ReverseParameters> {
    @Override
    public void execute() {
        parameters.destinationFile.get().text = parameters.fileToReverse.get().text.reverse()
    }
}
// end::unit-of-work[]

// tag::task-implementation[]
class ReverseFiles extends SourceTask {
    final WorkerExecutor workerExecutor

    @OutputDirectory
    File outputDir

    // The WorkerExecutor will be injected by Gradle at runtime
    @Inject
    public ReverseFiles(WorkerExecutor workerExecutor) {
        this.workerExecutor = workerExecutor
    }

    @TaskAction
    void reverseFiles() {
        // Create a WorkQueue to submit work items
        WorkQueue workQueue = workerExecutor.noIsolation()
        
        // Create and submit a unit of work for each file
        source.each { file ->
            workQueue.submit(ReverseFile.class) { ReverseParameters parameters ->
                parameters.fileToReverse = file
                parameters.destinationFile = project.file("$outputDir/${file.name}")
            }
        }
    }
}
// end::task-implementation[]

task reverseFiles(type: ReverseFiles) {
    outputDir = file("$buildDir/reversed")
    source("sources")
}
