package com.example.studyapp.update

import android.util.Log
import com.example.studyapp.pad.Pad
import com.example.studyapp.pad.PadTask
import com.example.studyapp.pad.TaskDetail
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.json.JSONArray
import org.json.JSONObject
import kotlin.apply
import kotlin.collections.isNotEmpty
import kotlin.to
import kotlin.toString

object Api {
    private const val TAG = "Api"
    const val UPDATE_PAD: String = "/openapi/open/pad/updatePadProperties"
    const val PAD_DETAIL: String = "/openapi/open/pad/padDetails"
    const val PAD_TASK: String = "/task-center/open/task/padTaskDetail"


    fun padDetail(): ApiResponse<Pad>{
        val param = Gson().toJson(
            mapOf(
                "page" to 1,
                "rows" to 10,
                "padCode" to listOf("ACP250702PWJCTLF")
            )
        )
        val (response, code) = HttpUtils.postSync(PAD_DETAIL, param)
        if (code == 200) {
            Log.d("padDetail", response.toString())
            var apiResponse: ApiResponse<Pad> =  Gson().fromJson(response, object : TypeToken<ApiResponse<Pad>>() {}.type)
            return apiResponse
        } else {
            Log.d("padDetail", "error: $code")
            return ApiResponse(code, "error", 0, null)
        }
    }

    fun updatePad(params: String): ApiResponseList<PadTask>{
        val (response, code) = HttpUtils.postSync(UPDATE_PAD, params)
        if (code == 200) {
            Log.d("updatePad", response.toString())
            var apiResponse: ApiResponseList<PadTask> = Gson().fromJson(response, object : TypeToken<ApiResponseList<PadTask>>() {}.type)
            return apiResponse
        } else {
            Log.d("updatePad", "error: $code")
            return ApiResponseList(code, "error", 0, emptyList())
        }
    }

    fun padTaskDetail(taskId: Int): Int{
        val jsonString = JSONObject().apply {
            put("taskIds", JSONArray().apply {
                put(taskId)
            })
        }.toString()
        Log.d(TAG, "padTaskDetail: $jsonString")
        val (response, code) = HttpUtils.postSync(PAD_TASK, jsonString)
        if (code == 200) {
            Log.d("padTaskDetail", response.toString())
            var apiResponse: ApiResponseList<TaskDetail> = Gson().fromJson(response, object : TypeToken<ApiResponseList<TaskDetail>>() {}.type)
            val taskList = apiResponse.data
            if (apiResponse.isSuccess() && taskList!= null && taskList.isNotEmpty()){
                val task = taskList[0]
                return task.taskStatus
            }
            return -1
        }else {
            Log.d("padTaskDetail", "error: $code")
            return -1
        }
    }
}