/*
 * Copyright (c) 2023 codvision.com All Rights Reserved.
 */

package com.codvision.webcore.util;

import cn.hutool.core.util.ClassLoaderUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * WebUtil
 *
 * @author lingee
 * @date 2024/1/23
 */
@Slf4j
public class WebUtil {


    /**
     * 打印程序相关地址
     *
     * @param env 当前环境
     */
    public static void printWebUrl(Environment env) {
        try {
            String ip = InetAddress.getLocalHost().getHostAddress();
            String applicationName = env.getProperty("spring.application.name");
            if (StrUtil.isBlank(applicationName)) {
                applicationName = "";
            }
            String port = env.getProperty("server.port");
            String path = env.getProperty("server.servlet.context-path");
            if (StrUtil.isBlank(path)) {
                path = "";
            } else {
                if (StrUtil.contains(path, "/")) {
                    path = "/" + StrUtil.removeAll(path, "/");
                }
            }
            String backend = "";
            if (ClassLoaderUtil.isPresent("com.codvision.base.config.BaseConfig")) {
                backend = "Backend: \t\thttp://" + ip + ":" + port + path + "/backend/index.html\n\t";
            }
            log.info("\n----------------------------------------------------------\n\t" +
                    "Application " + applicationName + " is running! Access URLs:\n\t" +
                    "Local: \t\thttp://127.0.0.1:" + port + path + "/\n\t" + backend +
                    "Doc: \t\thttp://" + ip + ":" + port + path + "/doc.html\n" +
                    "----------------------------------------------------------");
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
    }
}
