package mobvista.dmp.output.reyun

import mobvista.dmp.common.{CommonSparkJob, MobvistaConstant}
import mobvista.dmp.output.reyun.Constant._
import org.apache.commons.cli.Options
import org.apache.spark.sql.SaveMode

/**
 * @package: mobvista.dmp.output.reyun
 * @author: wangjf
 * @date: 2021/9/14
 * @time: 2:06 下午
 * @email: jinfeng.wang@mobvista.com
 */
class TrackingLog extends CommonSparkJob {
  override protected def buildOptions(): Options = {
    val options = new Options
    options.addOption("log_type", true, "[must] log_type")
    options.addOption("date", true, "[must] date")
    options.addOption("output", true, "[must] output")
    options.addOption("coalesce", true, "[must] coalesce")
    options
  }

  override protected def run(args: Array[String]): Int = {
    val commandLine = commParser.parse(options, args)
    if (!checkMustOption(commandLine)) {
      printUsage(options)
      return -1
    } else {
      printOptions(commandLine)
    }
    val log_type = commandLine.getOptionValue("log_type")
    val date = commandLine.getOptionValue("date")
    val output = commandLine.getOptionValue("output")
    val coalesce = Integer.parseInt(commandLine.getOptionValue("coalesce"))

    val spark = MobvistaConstant.createSparkSession(s"TrackingLog.${log_type}.${date}")

    try {

      val year = date.substring(0, 4)
      val month = date.substring(4, 6)
      val day = date.substring(6, 8)

      val sql =
        log_type match {
          case "impression" =>
            tracking_impression
          case "install" =>
            tracking_install
          case "click" =>
            tracking_click
        }
      val df = spark.sql(sql.replace("@year", year)
        .replace("@month", month)
        .replace("@day", day))

      df.repartition(coalesce)
        .write
        .mode(SaveMode.Overwrite)
        .option("orc.compress", "zlib")
        .orc(output)
    } finally {
      spark.stop()
    }
    0
  }
}

object TrackingLog {
  def main(args: Array[String]): Unit = {
    new TrackingLog().run(args)
  }
}