/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 org.apache.lucene.gradle.plugins.help.ExecOperationsProvider

description = 'OpenNLP Library Integration'

dependencies {
  moduleApi project(':lucene:core')
  moduleApi project(':lucene:analysis:common')
  moduleApi deps.opennlp.tools

  moduleTestImplementation project(':lucene:test-framework')
}

ext {
  testModelDataDir = file('src/tools/test-model-data')
  testsUserDir = file('src/test-files')
  testModelDir = file("${testsUserDir}/org/apache/lucene/analysis/opennlp")
}

// this should be hooked to regenerate?
tasks.register('trainTestModels') {
  description = 'Train all small test models for unit tests'
  doLast {
    mkdir testModelDir
    trainModel('SentenceDetectorTrainer', 'en', 'sentences.txt', 'en-test-sent.bin')
    trainModel('TokenizerTrainer', 'en', 'tokenizer.txt', 'en-test-tokenizer.bin')
    trainModel('POSTaggerTrainer', 'en', 'pos.txt', 'en-test-pos-maxent.bin')
    trainModel('ChunkerTrainerME', 'en', 'chunks.txt', 'en-test-chunker.bin')
    trainModel('TokenNameFinderTrainer', 'en', 'ner.txt', 'en-test-ner.bin', [
      '-params',
      'ner_TrainerParams.txt'
    ])
    trainModel('LemmatizerTrainerME', 'en', 'lemmas.txt', 'en-test-lemmatizer.bin')
  }
}

def trainModel(String command, String lang, String data, String model, List extraArgs = []) {
  def execOps = objects.newInstance(ExecOperationsProvider).execOperations
  execOps.javaexec {
    classpath = sourceSets.main.compileClasspath
    mainClass = 'opennlp.tools.cmdline.CLI'
    workingDir = testModelDataDir
    args = [
      command,
      '-lang',
      lang,
      '-data',
      data,
      '-model',
      "${testModelDir}/${model}"
    ] + extraArgs
  }
}
