package com.ruoyi.robot.service.impl;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.robot.domain.LdTilemapConfig;
import com.ruoyi.robot.mapper.LdTilemapConfigMapper;
import com.ruoyi.robot.service.ILdTilemapConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 瓦片地图配置Service实现
 */
@Service
public class LdTilemapConfigServiceImpl implements ILdTilemapConfigService {

    @Autowired
    private LdTilemapConfigMapper tilemapConfigMapper;

    @Autowired
    private RedisCache redisCache;

    @Value("${tilemap.storage.path:/data/tilemap}")
    private String defaultStoragePath;

    @Value("${tilemap.base-url:http://localhost:8080/tilemap}")
    private String defaultBaseUrl;

    private static final String TILEMAP_CACHE_KEY = "ld:tilemap:config:";

    @Override
    public LdTilemapConfig selectTilemapConfigByMapName(String mapName) {
        String cacheKey = TILEMAP_CACHE_KEY + mapName;

//        LdTilemapConfig cached = redisCache.getCacheObject(cacheKey);
//        if (cached != null) {
//            return cached;
//        }

        LdTilemapConfig config = tilemapConfigMapper.selectByMapName(mapName);

//        if (config != null) {
//            redisCache.setCacheObject(cacheKey, config);
//        }

        return config;
    }

    @Override
    public String getTilePath(String mapName, int zoom, int x, int y) {
        LdTilemapConfig config = selectTilemapConfigByMapName(mapName);
        if (config == null) {
            return null;
        }

        String storagePath = config.getTileStoragePath();
        if (storagePath == null || storagePath.isEmpty()) {
            storagePath = defaultStoragePath + "/" + mapName;
        }

        // 瓦片路径格式: /path/mapName/zoom/x/y.png
        String format = config.getFormat() != null ? config.getFormat() : "png";
        return String.format("%s/%s/%d/%d/%d.%s", storagePath, mapName, zoom, x, y, format);
    }

    @Override
    public String getTileUrl(String mapName, int zoom, int x, int y) {
        LdTilemapConfig config = selectTilemapConfigByMapName(mapName);
        if (config == null) {
            return null;
        }

        String baseUrl = config.getTileBaseUrl();
        if (baseUrl == null || baseUrl.isEmpty()) {
            baseUrl = defaultBaseUrl + "/" + mapName;
        }

        String format = config.getFormat() != null ? config.getFormat() : "png";
        return String.format("%s/%d/%d/%d.%s", baseUrl, zoom, x, y, format);
    }
}
