package mobvista.dmp.datasource.dm

import java.net.URI

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

/**
  * @package: mobvista.dmp.datasource.dm
  * @author: wangjf
  * @date: 2018/11/27
  * @time: 下午4:36
  * @email: jinfeng.wang@mobvista.com
  * @phone: 152-1062-7698
  */
class DmInstallListOrc extends CommonSparkJob with Serializable {

  override protected def run(args: Array[String]): Int = {
    val commandLine = commParser.parse(options, args)
    if (!checkMustOption(commandLine)) {
      printUsage(options)
      printOptions(commandLine)
      return 1
    } else {
      printOptions(commandLine)
    }

    val business = commandLine.getOptionValue("business")
    val date = commandLine.getOptionValue("date")
    val output = commandLine.getOptionValue("output")

    val spark = SparkSession.builder()
      .appName(name = s"DmInstallListOrc.$business")
      .config("spark.sql.orc.filterPushdown", "true")
      .config("spark.rdd.compress", "true")
      .config("spark.io.compression.codec", "snappy")
      .config("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
      .enableHiveSupport()
      .getOrCreate()

    FileSystem.get(new URI(s"s3://mob-emr-test"), spark.sparkContext.hadoopConfiguration).delete(new Path(output), true)
    try {

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

      val df = spark.sql(sql).rdd
        .flatMap(Constant.orcMap)

      spark.createDataFrame(df, Constant.schema)
        .write
        .mode(SaveMode.Overwrite)
        .option("orc.compress", "zlib")
        .orc(output)

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

  override protected def buildOptions(): Options = {
    val options = new Options
    options.addOption("business", true, "[must] business")
    options.addOption("date", true, "[must] date")
    options.addOption("output", true, "[must] output path")
    options
  }
}

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