package gaf3.core.services.menu

import com.alibaba.fastjson.JSON
import gaf3.core.data.JsonResult
import gaf3.core.exception.BusinessError
import gaf3.core.services.menu.domain.MenuItem
import gaf3.core.services.menu.service.GafMenuStore
import org.apache.commons.io.IOUtils
import org.slf4j.LoggerFactory
import org.springframework.http.server.reactive.ServerHttpResponse
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
import java.io.FileNotFoundException
import java.nio.charset.Charset

@RestController
class GafMenuServiceController(val service: GafMenuStore, val config: GafMenuConfigure) {
    /**
     * 树状导航菜单
     */
    @GetMapping(path = ["/gaf/menu/items"])
    fun tree(res: ServerHttpResponse): JsonResult<List<MenuItem>> {
        val rs = service.load()
        return with(JsonResult(rs)) {
            this.errmsg = "ok"
            this
        }
    }

    /**
     * 横向导航条菜单
     */
    @GetMapping(path = ["/gaf/menu/menus"])
    fun menus(res: ServerHttpResponse): JsonResult<List<MenuItem>> {
        try {
            val jsonData = IOUtils.toString(config.itemsFile.inputStream, Charset.forName("UTF-8"))
            val menus = JSON.parseArray(jsonData, MenuItem::class.java)
            return with(JsonResult(menus)) {
                this.errmsg = "ok"
                this
            }
        } catch (ex: FileNotFoundException) {
            log.error(ex.message)
            if(log.isDebugEnabled) {
                ex.printStackTrace()
            }
            throw BusinessError(BusinessError.ERR_SERVICE_FAULT, "菜单文件不存在")
        }
    }

    companion object {
        internal val log = LoggerFactory.getLogger(GafMenuServiceController::class.java)
    }
}