package mobvista.dmp.datasource.toutiao

import java.net.URI
import java.util
import java.util.Base64

import mobvista.dmp.common.CommonSparkJob
import org.apache.commons.cli.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.toutiao
  * @author: wangjf
  * @date: 2019/2/22
  * @time: 下午5:07
  * @email: jinfeng.wang@mobvista.com
  * @phone: 152-1062-7698
  */
class CheckToutiao extends CommonSparkJob with Serializable {

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

    val input = commandLine.getOptionValue("input")
    val output = commandLine.getOptionValue("output")

    val spark = SparkSession.builder()
      .appName("CheckToutiao")
      .config("spark.rdd.compress", "true")
      .config("spark.io.compression.codec", "snappy")
      .config("spark.sql.orc.filterPushdown", "true")
      .config("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
      .config("spark.sql.warehouse.dir", "s3://mob-emr-test/spark-warehouse")
      .enableHiveSupport()
      .getOrCreate()

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

    try {
      val sc = spark.sparkContext
      val rdd = sc.textFile(input)
        .flatMap(v => {
          val res = new util.ArrayList[(String, Int)]()
          val vs = Base64.getDecoder.decode(v)
          val dmpData = DmpDataProto.DmpData.parseFrom(vs)
          val dmpDataIter = dmpData.getIdListList.iterator()
          while (dmpDataIter.hasNext) {
            val tags = dmpDataIter.next().getTagsList.iterator()
            while (tags.hasNext) {
              res.add((tags.next, 1))
            }
          }
          import scala.collection.JavaConverters._
          res.asScala.iterator
        })
      rdd.reduceByKey(_ + _).sortByKey(true, 1).saveAsTextFile(output, classOf[GzipCodec])

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

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

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