package mobvista.dmp.datasource.adn_sdk

import com.google.gson.{JsonArray, JsonObject}
import mobvista.dmp.common.CommonInstallList
import mobvista.dmp.datasource.mpsdk.InstallInfo
import mobvista.prd.datasource.util.GsonUtil
import org.apache.commons.lang.StringUtils

import java.text.SimpleDateFormat
import java.util
import java.util.Date
import scala.collection.JavaConversions._
import scala.collection.mutable.ArrayBuffer

/**
 * 刘凯      2018-01-19 11:30
 * 将adn_sdk天数据合并到安装列表全量数据中
 */
class AdnSdkInstallList extends CommonInstallList {
  /**
   * 解析天处理结果数据
   *
   * @param array
   * @param date
   * @return
   */
  val time_format = new SimpleDateFormat("yyyy-MM-dd")
  val date = new Date()
  val ins_day = time_format.format(date)

  def processDailyData(array: Array[String], date: String): Array[(String, InstallInfo)] = {
    val buffer = new ArrayBuffer[(String, InstallInfo)]()
    if (array.length >= 4) {
      val device_id = array(0)
      val device_type = array(1)
      val platform = array(2)
      val pkgList = array(7)
      val set = new util.HashSet[InstallInfo]()
      val jsonArray = GsonUtil.String2JsonArray(pkgList)
      val installArray = new JsonArray()
      jsonArray.foreach(element => {
        val package_name = if (element != null && !element.isJsonNull && element.getAsJsonObject.has("package_name")) {
          element.getAsJsonObject.get("package_name").getAsString
        } else {
          ins_day
        }
        if (StringUtils.isNotBlank(package_name)) {
          val jsonObject = new JsonObject()
          val date = if (element.getAsJsonObject.has("date") && StringUtils.isNotBlank(element.getAsJsonObject.get("date").getAsString)) {
            element.getAsJsonObject.get("date").getAsString
          } else {
            ins_day
          }
          jsonObject.addProperty("package_name", package_name)
          jsonObject.addProperty("date", date)
          installArray.add(jsonObject)
        }
      })
      installArray.foreach(element => {
        set.add(GsonUtil.fromJson(element, classOf[InstallInfo]))
      })
      set.iterator()
        .foreach(installInfo => {
          buffer += Tuple2(s"$device_id$FIELD_SPLIT$device_type$FIELD_SPLIT$platform", installInfo)
        })
    }
    buffer.toArray
  }
}

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