package org.dromara.web.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.SpringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.Manifest;

@SaIgnore
@RestController
@RequestMapping("/deploy")
public class DeployInfoController {

    @GetMapping("/info")
    public R<Map<String, Object>> info() {
        String version = null;
        String buildTime = null;
        String startClass = null;
        try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("META-INF/MANIFEST.MF")) {
            if (is != null) {
                Manifest mf = new Manifest(is);
                version = mf.getMainAttributes().getValue("Implementation-Version");
                buildTime = mf.getMainAttributes().getValue("Build-Time");
                startClass = mf.getMainAttributes().getValue("Start-Class");
            }
        } catch (Exception ignored) {
        }
        Map<String, Object> data = new HashMap<>();
        data.put("application", SpringUtils.getApplicationName());
        data.put("version", version);
        if (buildTime != null) {
            try {
                Instant instant = Instant.parse(buildTime);
                buildTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
                        .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            } catch (Exception ignored) {
            }
        }
        data.put("buildTime", buildTime);
        data.put("startClass", startClass);
        data.put("serverTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        return R.ok(data);
    }
}
