package mobvista.dmp.datasource.retargeting

import java.net.URI

import mobvista.dmp.common.CommonSparkJob
import mobvista.dmp.util.MRUtils
import org.apache.commons.cli.{BasicParser, Options}
import org.apache.hadoop.fs.{FileSystem, Path}
import org.apache.hadoop.io.compress.GzipCodec
import org.apache.spark.sql.SparkSession

/**
  * @package: mobvista.dmp.datasource.retargeting
  * @author: wangjf
  * @date: 2019-06-06
  * @time: 17:29
  * @emial: jinfeng.wang@mobvista.com
  * @phone: 152-1062-7698
  */
class PackageMapping extends CommonSparkJob {

  def commandOptions(): Options = {
    val options = new Options()
    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 output = commandLine.getOptionValue("output")
    val spark = SparkSession
      .builder()
      .appName("PackageMapping")
      .config("spark.rdd.compress", "true")
      .config("spark.shuffle.compress", "true")
      .config("spark.io.compression.codec", "lz4")
      .config("spark.io.compression.lz4.blockSize", "64k")
      .config("spark.sql.autoBroadcastJoinThreshold", "209715200")
      .config("spark.sql.warehouse.dir", "s3://mob-emr-test/spark-warehouse")
      .enableHiveSupport()
      .getOrCreate()
    try {
      val mysqlDF = Constant.jdbcConnection(spark, "mob_adn", "dmp_app_map").rdd.map(r => {
        MRUtils.JOINER.join(r.getAs("id").toString, r.getAs("app_package_name").toString)
      })

      FileSystem.get(new URI(s"s3://mob-emr-test"), spark.sparkContext.hadoopConfiguration).delete(new Path(output), true)
      mysqlDF.repartition(10)
        .saveAsTextFile(output, classOf[GzipCodec])
    } finally {
      if (spark != null) {
        spark.stop()
      }
    }
    0
  }
}

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