package com.lanyuanxiaoyao.digtal.market.controller

import cn.hutool.json.JSON
import cn.hutool.json.JSONUtil
import com.lanyuanxiaoyao.digtal.market.ArticleRepository
import com.lanyuanxiaoyao.squirrel.core.jvm.JvmManagement
import jakarta.annotation.Resource
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController

@ExperimentalStdlibApi
@RestController
@RequestMapping("site")
class SiteController {
    private val logger = LoggerFactory.getLogger(javaClass)

    @Resource
    private lateinit var articleRepository: ArticleRepository

    @Resource
    private lateinit var management: JvmManagement

    @GetMapping("list")
    fun list(): List<Map<String, Any>> {
        val countMap = articleRepository.countGroupByCode().associate { it.key to it.count }
        return management.exportSites()
            .map { site ->
                mapOf(
                    "code" to site.code,
                    "name" to site.name,
                    "icon" to site.icon,
                    "url" to site.home,
                    "description" to site.description,
                    "iframe" to site.properties.containsKey("iframe"),
                    "news" to (countMap[site.code] ?: 0)
                )
            }
    }

    @GetMapping("source")
    fun source(@RequestParam("code") code: String) = management.exportSites()
        .find { it.code == code }
}