package com.example.modifier.http.api

import com.example.modifier.http.ktorClient
import com.example.modifier.http.response.DeviceResponse
import io.ktor.client.call.body
import io.ktor.client.plugins.resources.get
import io.ktor.client.plugins.resources.post
import io.ktor.resources.Resource
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@Resource("api/device")
class DeviceApi() {

    @Resource("{id}")
    class Id(val parent: DeviceApi = DeviceApi(), val id: String) {

        @Resource("removePinTask")
        class RemovePinTask(val parent: Id) {}
    }

    companion object {
        suspend fun getDevice(deviceId: String): DeviceResponse {
            try {
                return ktorClient.get(Id(id = deviceId))
                    .body<DeviceResponse>()
            } catch (_: Exception) {
            }
            return DeviceResponse(
                id = deviceId,
                pinCountry = null,
                clashProfile = null
            )
        }

        fun removePinTask(deviceId: String) {
            CoroutineScope(Dispatchers.IO).launch {
                runCatching {
                    ktorClient.post(Id.RemovePinTask(Id(id = deviceId))).body<String>()
                }
            }
        }
    }
}