package mobvista.dmp.datasource.datatory

import java.net.URI

import mobvista.dmp.common.CommonSparkJob
import org.apache.commons.cli.{BasicParser, Options}
import org.apache.hadoop.fs.{FileSystem, Path}
import org.apache.spark.broadcast.Broadcast
import org.apache.spark.sql.{SaveMode, SparkSession}

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

    options
  }

  var cityMap: Broadcast[scala.collection.Map[String, String]] = null
  var appMap: Broadcast[scala.collection.Map[String, String]] = null

  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("AdnTrackingInstallDaily")
      .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 {
      FileSystem.get(new URI(s"s3://mob-emr-test"), sc.hadoopConfiguration).delete(new Path(output), true)

      cityMap = sc.broadcast(Constant.jdbcConnection(spark, "mob_adn", "city")
        .select("id", "name", "country", "country_code")
        .rdd.map(r => {
        (r.getAs("id").toString, r.getAs("name").toString)
      }).collectAsMap())

      spark.udf.register("getCity", getCity _)

      val sql = Constant.adn_tracking_install_sql.replace("@date", date)

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

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

  def getCity(id: String): String = {
    cityMap.value.getOrElse(id, "")
  }

  def getChannel(id: String): String = {
    appMap.value.getOrElse(id, "")
  }
}


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