package com.example.vastlib.service

import com.example.vastlib.entity.http.Request
import com.example.vastlib.entity.report.TaskExec
import com.example.vastlib.entity.request.BaseRequestBuilder
import com.example.vastlib.utils.AndroidIdManager
import com.example.vastlib.utils.HttpUtils
import com.example.vastlib.utils.HttpUtils.HttpRequest.call
import com.example.vastlib.utils.JSONUtils
import com.example.vastlib.utils.JSONUtils.toJsonString
import com.example.vastlib.utils.LogUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class TaskReportService(private val taskExec: TaskExec, private val reportUrl: String) {

    suspend fun run() = withContext(Dispatchers.IO) {
        buildReportRequest().call()
    }

    private fun buildReportRequest(): Request = Request(url = reportUrl,
        headers = mapOf(
            HttpUtils.Params.REQUEST_HEADER_CONTENT_TYPE to HttpUtils.Params.REQUEST_HEADER_CONTENT_TYPE_STREAM,
            HttpUtils.Params.REQUEST_HEADER_ACCEPT to HttpUtils.Params.REQUEST_HEADER_CONTENT_TYPE_STREAM
        ),
        method = HttpUtils.Params.REQUEST_METHOD_POST,
        body = BaseRequestBuilder(AndroidIdManager.context).genReportRequest.run {
            this.taskLogs = listOf(taskExec)
            this.toJsonString().apply {
                LogUtils.info("request-data: $this")
            }.toByteArray()
        })
}