/**
 * 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.gateway.nacos;

import com.alibaba.nacos.api.config.convert.NacosConfigConverter;
import com.crunii.micro.common.utils.JsonUtil;
import com.crunii.micro.common.utils.YmlUtil;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 田平 create 2019年6月26日下午3:21:56
 */
public class DynamicRouteConverter implements NacosConfigConverter<List<RouteDefinition>> {

	private static final String ROUTES_PATH = "spring.cloud.gateway.routes";

	@Override
	public boolean canConvert(Class<List<RouteDefinition>> targetType) {
		return true;
	}

	@Override
	public List<RouteDefinition> convert(String config) {
		return convertConfig(config);
	}

	public static List<RouteDefinition> convertConfig(String config) {
		if (StringUtils.hasText(config)) {
			JsonNode routesNode = YmlUtil.getJsonNodeByPath(config, ROUTES_PATH);
			return JsonUtil.jsonToList(routesNode.toString(), RouteDefinition.class);
		} else {
			return new ArrayList<>(0);
		}
	}

}
