/*
 * 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.
 */

package org.apache.spark.sql.execution.python

import java.io.DataOutputStream
import java.util

import org.apache.spark.api.python._
import org.apache.spark.internal.config.{ConfigEntry, OptionalConfigEntry}
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.execution.metric.SQLMetric
import org.apache.spark.sql.execution.python.EvalPythonExec.ArgumentMetadata
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types._
import org.apache.spark.sql.util.ArrowUtils
import org.apache.spark.sql.vectorized.ColumnarBatch

abstract class BaseArrowPythonRunner[IN, OUT <: AnyRef](
    funcs: Seq[(ChainedPythonFunctions, Long)],
    evalType: Int,
    argOffsets: Array[Array[Int]],
    override protected val schema: StructType,
    override protected val timeZoneId: String,
    protected override val largeVarTypes: Boolean,
    override val pythonMetrics: Map[String, SQLMetric],
    jobArtifactUUID: Option[String],
    sessionUUID: Option[String])
  extends BasePythonRunner[IN, OUT](
    funcs.map(_._1), evalType, argOffsets, jobArtifactUUID, pythonMetrics)
  with PythonArrowInput[IN]
  with PythonArrowOutput[OUT] {
  ArrowUtils.failDuplicatedFieldNames(schema)

  override val envVars: util.Map[String, String] = {
    val envVars = new util.HashMap(funcs.head._1.funcs.head.envVars)
    sessionUUID.foreach { uuid =>
      envVars.put("PYSPARK_SPARK_SESSION_UUID", uuid)
    }
    envVars
  }
  override val pythonExec: String =
    SQLConf.get.pysparkWorkerPythonExecutable.getOrElse(
      funcs.head._1.funcs.head.pythonExec)

  override val faultHandlerEnabled: Boolean = SQLConf.get.pythonUDFWorkerFaulthandlerEnabled
  override val idleTimeoutSeconds: Long = SQLConf.get.pythonUDFWorkerIdleTimeoutSeconds
  override val killOnIdleTimeout: Boolean = SQLConf.get.pythonUDFWorkerKillOnIdleTimeout
  override val tracebackDumpIntervalSeconds: Long =
    SQLConf.get.pythonUDFWorkerTracebackDumpIntervalSeconds
  override val killWorkerOnFlushFailure: Boolean =
    SQLConf.get.pythonUDFDaemonKillWorkerOnFlushFailure

  override val hideTraceback: Boolean = SQLConf.get.pysparkHideTraceback
  override val simplifiedTraceback: Boolean = SQLConf.get.pysparkSimplifiedTraceback

  override val bufferSize: Int = SQLConf.get.pandasUDFBufferSize
  require(
    bufferSize >= 4,
    "Pandas execution requires more than 4 bytes. Please set higher buffer. " +
      s"Please change '${SQLConf.PANDAS_UDF_BUFFER_SIZE.key}'.")
}

abstract class RowInputArrowPythonRunner(
    funcs: Seq[(ChainedPythonFunctions, Long)],
    evalType: Int,
    argOffsets: Array[Array[Int]],
    schema: StructType,
    timeZoneId: String,
    largeVarTypes: Boolean,
    pythonMetrics: Map[String, SQLMetric],
    jobArtifactUUID: Option[String],
    sessionUUID: Option[String])
  extends BaseArrowPythonRunner[Iterator[InternalRow], ColumnarBatch](
    funcs, evalType, argOffsets, schema, timeZoneId, largeVarTypes,
    pythonMetrics, jobArtifactUUID, sessionUUID)
  with BasicPythonArrowInput
  with BasicPythonArrowOutput

/**
 * Similar to `PythonUDFRunner`, but exchange data with Python worker via Arrow stream.
 */
class ArrowPythonRunner(
    funcs: Seq[(ChainedPythonFunctions, Long)],
    evalType: Int,
    argOffsets: Array[Array[Int]],
    schema: StructType,
    timeZoneId: String,
    largeVarTypes: Boolean,
    pythonRunnerConf: Map[String, String],
    pythonMetrics: Map[String, SQLMetric],
    jobArtifactUUID: Option[String],
    sessionUUID: Option[String])
  extends RowInputArrowPythonRunner(
    funcs, evalType, argOffsets, schema, timeZoneId, largeVarTypes,
    pythonMetrics, jobArtifactUUID, sessionUUID) {

  override protected def runnerConf: Map[String, String] = super.runnerConf ++ pythonRunnerConf

  override protected def writeUDF(dataOut: DataOutputStream): Unit =
    PythonUDFRunner.writeUDFs(dataOut, funcs, argOffsets)
}

/**
 * Similar to `PythonUDFWithNamedArgumentsRunner`, but exchange data with Python worker
 * via Arrow stream.
 */
class ArrowPythonWithNamedArgumentRunner(
    funcs: Seq[(ChainedPythonFunctions, Long)],
    evalType: Int,
    argMetas: Array[Array[ArgumentMetadata]],
    schema: StructType,
    timeZoneId: String,
    largeVarTypes: Boolean,
    pythonRunnerConf: Map[String, String],
    pythonMetrics: Map[String, SQLMetric],
    jobArtifactUUID: Option[String],
    sessionUUID: Option[String])
  extends RowInputArrowPythonRunner(
    funcs, evalType, argMetas.map(_.map(_.offset)), schema, timeZoneId, largeVarTypes,
    pythonMetrics, jobArtifactUUID, sessionUUID) {

  override protected def runnerConf: Map[String, String] = super.runnerConf ++ pythonRunnerConf

  override protected def evalConf: Map[String, String] = {
    if (evalType == PythonEvalType.SQL_ARROW_BATCHED_UDF) {
      super.evalConf ++ Map(
        "input_type" -> schema.json
      )
    } else {
      super.evalConf
    }
  }

  override protected def writeUDF(dataOut: DataOutputStream): Unit = {
    PythonUDFRunner.writeUDFs(dataOut, funcs, argMetas)
  }
}

object ArrowPythonRunner {
  /** Return Map with conf settings to be used in ArrowPythonRunner */
  def getPythonRunnerConfMap(conf: SQLConf): Map[String, String] = {
    val confMap = collection.mutable.Map.empty[String, String]
    Seq(
      SQLConf.SESSION_LOCAL_TIMEZONE,
      SQLConf.PANDAS_GROUPED_MAP_ASSIGN_COLUMNS_BY_NAME,
      SQLConf.PANDAS_ARROW_SAFE_TYPE_CONVERSION,
      SQLConf.ARROW_EXECUTION_USE_LARGE_VAR_TYPES,
      SQLConf.PYTHON_TABLE_UDF_LEGACY_PANDAS_CONVERSION_ENABLED,
      SQLConf.PYTHON_UDF_LEGACY_PANDAS_CONVERSION_ENABLED,
      SQLConf.PYTHON_UDF_PANDAS_INT_TO_DECIMAL_COERCION_ENABLED,
      SQLConf.PYTHON_UDF_PANDAS_PREFER_INT_EXTENSION_DTYPE,
      SQLConf.PYSPARK_BINARY_AS_BYTES,
      // Optional
      SQLConf.PYTHON_UDF_ARROW_CONCURRENCY_LEVEL,
      SQLConf.PYTHON_UDF_PROFILER,
      SQLConf.PYTHON_DATA_SOURCE_PROFILER
    ).foreach {
      case c: OptionalConfigEntry[_] =>
        conf.getConf(c).foreach(v => confMap.update(c.key, v.toString))
      case c: ConfigEntry[_] =>
        confMap.update(c.key, conf.getConf(c).toString)
    }
    confMap.toMap
  }
}
