/*
 * Copyright (c) 2018 無色眼镜
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package club.dawdler.jedis.health;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import club.dawdler.core.health.Health;
import club.dawdler.core.health.Health.Builder;
import club.dawdler.core.health.HealthIndicator;
import club.dawdler.jedis.UnifiedJedisFactory;
import club.dawdler.jedis.UnifiedJedisWrapper;

/**
 * @author jackson.song
 * @version V1.0
 * JedisIndicator jedis健康指示器
 */
public class JedisIndicator implements HealthIndicator {

	private static final String VERSION_PREFIX = "redis_version:";

	@Override
	public String name() {
		return "jedis";
	}

	@Override
	public Health check(Builder builder) throws Exception {
		Map<String, UnifiedJedisWrapper> unifiedJedisCache = UnifiedJedisFactory.getUnifiedJedisCache();
		Set<Map.Entry<String, UnifiedJedisWrapper>> entrySet = unifiedJedisCache.entrySet();
		for (Entry<String, UnifiedJedisWrapper> entry : entrySet) {
			String key = entry.getKey();
			UnifiedJedisWrapper unifiedJedisWrapper = entry.getValue();
			Builder childBuilder = Health.up();
			childBuilder.withDetail("version", getRedisVersion(unifiedJedisWrapper.getUnifiedJedis().info("Server")));
			builder.withDetail(key, childBuilder.build().getData());
		}
		return builder.build();
	}

	private String getRedisVersion(String info) {
		for (String line : info.split("\\R")) {
			if (line.startsWith(VERSION_PREFIX)) {
				return line.substring(VERSION_PREFIX.length()).trim();
			}
		}
		return "unknown";
	}

}
