package mobvista.dmp.datasource.adn_request_sdk

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.sql.{SaveMode, SparkSession}
import org.apache.spark.sql.functions._

/**
  * @package: mobvista.dmp.datasource.adn_sdk
  * @author: wangjf
  * @date: 2020/4/2
  * @time: 8:34 下午
  * @email: jinfeng.wang@mobvista.com
  * @phone: 152-1062-7698
  */
class AdnRequestSdkRegionDaily extends CommonSparkJob with java.io.Serializable {
  def commandOptions(): Options = {
    val options = new Options()
    options.addOption("output", true, "output")
    options.addOption("coalesce", true, "coalesce")
    options
  }

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

    val spark = SparkSession
      .builder()
      .appName(s"AdnRequestSdkRegionDaily")
      .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)

      spark.sql(Constant.adn_sql).coalesce(coalesce).dropDuplicates
        .union(spark.sql(Constant.dsp_sql).coalesce(coalesce).dropDuplicates)
        .groupBy("devid", "region")
        .agg(concat_ws(",", collect_set("system")).as("system"))
        .repartition(1000)
        .write
        .mode(SaveMode.Overwrite)
        .option("orc.compress", "snappy")
        .orc(output)

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

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