/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved.
 * <a>http://www.crunii.com</a>
 */
package com.crunii.micro.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.google.common.base.Splitter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.util.Iterator;

/**
 * @author 田平 create 2023-02-16 15:00:15
 */
@Slf4j
public class YmlUtil {

	private static ObjectMapper mapper = new ObjectMapper(new YAMLFactory());

	static {
		mapper.findAndRegisterModules();
	}

	public ObjectMapper getYmlObjectMapper() {
		return mapper;
	}

	public static <T> T yml2Object(String ymlContent, Class<T> clazz) {
		T t = null;
		try {
			t = mapper.readValue(ymlContent, clazz);
		} catch (JsonProcessingException e) {
			throw new RuntimeException("yml字符串转换Object出错！", e);
		}
		return t;
	}

	public static JsonNode getRootJsonNode(String ymlContent) {
		JsonNode jsonNode = null;
		try {
			jsonNode = mapper.readTree(ymlContent);
		} catch (JsonProcessingException e) {
			throw new RuntimeException("yml字符串转换getJsonNode出错！", e);
		}
		return jsonNode;
	}

	public static JsonNode getJsonNodeByPath(String ymlContent, String path) {
		Assert.hasText(path, "path not allowed null");
		Assert.hasText(path, "ymlContent not allowed null");
		JsonNode root = getRootJsonNode(ymlContent);
		Iterator<String> iterator = Splitter.on('.')
				.trimResults()
				.omitEmptyStrings()
				.split(path).iterator();
		while (iterator.hasNext() && root != null) {
			root = root.path(iterator.next());
		}
		return root;
	}

	public static void main(String[] args) throws Exception {
		String path = "spring.cloud.gateway.routes";
		String yml = FileUtil.getFileContent("C:\\Users\\Administrator\\Desktop\\application-dynamic-routes.yml");
		JsonNode routesNode = YmlUtil.getJsonNodeByPath(yml, path);
		System.out.println(routesNode.toString());
	}

}
