
plugins {
  id 'java'
  id 'com.google.protobuf' version '0.8.16'
  id 'com.github.jlouns.cpe' version '0.5.0'
}

project.ext.set('protobufVersion', '3.16.0')
project.ext.set('protocVersion', project.protobufVersion)

def isWindows = System.getProperty('os.name').toLowerCase().contains('windows')

repositories {
  mavenCentral()
}

sourceSets {
  main {
    proto {
      srcDir file('./proto')
    }
  }
}

protobuf {
  protoc {
    if (osdetector.os == 'osx') {
      // Required for arm64 support on MacOS
      artifact = "com.google.protobuf:protoc:${protocVersion}:osx-x86_64"
    } else {
      artifact = "com.google.protobuf:protoc:${protocVersion}"
    }
  }
  plugins {
    grpc {
      path = file(
        './node_modules/.bin/grpc_tools_node_protoc_plugin' + (isWindows ? '.cmd' : '')
      )
    }
    ts {
      path = file(
        './node_modules/.bin/protoc-gen-ts' + (isWindows ? '.cmd' : '')
      )
    }
  }
  generateProtoTasks {
    generateProto.finalizedBy copyGeneratedProto
    all().each { task ->
      task.plugins {
        grpc {
          outputSubDir = 'js'
          option 'grpc_js'
        }
        ts {
          option 'service=grpc-node,mode=grpc-js'
        }
      }
      task.builtins {
        remove java
        js {
          option 'import_style=commonjs'
        }
      }
      task.dependsOn npmInstall
    }
  }
}

task copyGeneratedProto(type: Copy) {
  from "$protobuf.generatedFilesBaseDir/main/ts", "$protobuf.generatedFilesBaseDir/main/js"
  into 'proto'
}

task npmInstall(type: CrossPlatformExec) {
  description 'Installs node dependencies'
  inputs.file('package-lock.json').withPathSensitivity(PathSensitivity.RELATIVE)
  outputs.dir('node_modules')
  outputs.cacheIf { true }
  commandLine 'npm', 'install'
}
