package mobvista.dmp.datasource.backflow

import mobvista.dmp.common.{CommonSparkJob, MobvistaConstant}
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 java.net.URI


/**
 * @package: mobvista.dmp.datasource.backflow
 * @author: wangjf
 * @date: 2021/4/25
 * @time: 18:35 下午
 * @email: jinfeng.wang@mobvista.com
 */

class BackFlowFilter extends CommonSparkJob with 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 = MobvistaConstant.createSparkSession("BackFlowFilter")
    val sc = spark.sparkContext
    try {

      val df = spark.sql(BackFlowConstant.mapping_sql.replace("@dt", date))

      val pathUri = new URI(output)
      FileSystem.get(new URI(s"${pathUri.getScheme}://${pathUri.getHost}"), sc.hadoopConfiguration).delete(new Path(output), true)

      //  region, devid_key, devid_type, devid_value
      df.rdd.map(r => {
        MRUtils.JOINER.join(r.getAs[String]("region"), r.getAs[String]("devid_key"),
          r.getAs[String]("devid_type"), r.getAs[String]("devid_value"))
      }).repartition(50)
        .saveAsTextFile(output, classOf[GzipCodec])

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

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