package mobvista.dmp.datasource.datatory

import mobvista.dmp.common.CommonSparkJob
import org.apache.commons.cli.{BasicParser, Options}
import org.apache.spark.sql.{SaveMode, SparkSession}

/**
  * @package: mobvista.dmp.datasource.datatory
  * @author: wangjf
  * @date: 2019/4/25
  * @time: 下午3:19
  * @email: jinfeng.wang@mobvista.com
  * @phone: 152-1062-7698
  */
class TrackingInstallDaily extends CommonSparkJob with java.io.Serializable {
  def commandOptions(): Options = {
    val options = new Options()
    options.addOption("date", true, "date")
    options.addOption("output", true, "output")

    options
  }

  override protected def run(args: Array[String]): Int = {
    val parser = new BasicParser()
    val options = commandOptions()
    val commandLine = parser.parse(options, args)
    val date = commandLine.getOptionValue("date")
    val output = commandLine.getOptionValue("output")

    val spark = SparkSession
      .builder()
      .appName("TrackingInstallDaily")
      .config("spark.rdd.compress", "true")
      .config("spark.shuffle.compress", "true")
      .config("spark.sql.orc.filterPushdown", "true")
      .config("spark.io.compression.codec", "lz4")
      .config("spark.io.compression.lz4.blockSize", "64k")
      .config("spark.sql.warehouse.dir", "s3://mob-emr-test/spark-warehouse")
      .config("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
      .enableHiveSupport()
      .getOrCreate()

    val sc = spark.sparkContext
    try {
      //  spark.udf.register("check_deviceId", Constant.check_deviceId _)

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

      val sql = Constant.tracking_install_sql.replace("@year", year)
        .replace("@month", month)
        .replace("@day", day)
      //  .replace("@check_deviceId", "check_deviceId(devid)")

      spark.sql(sql)
        .filter(r => {
          Constant.check_deviceId(r.getAs("device_id"))
        })
        .write
        .mode(SaveMode.Overwrite)
        .option("orc.compress", "snappy")
        .orc(output)

    } finally {
      if (spark != null) {
        spark.stop()
      }
    }
    0
  }
}


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