package quant.rich.emoney.entity.config;

import java.io.IOException;
import org.springframework.context.annotation.Lazy;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.Data;
import lombok.experimental.Accessors;
import okhttp3.Request;
import okhttp3.Response;
import quant.rich.emoney.client.OkHttpClientProvider;
import quant.rich.emoney.component.CallerLockAspect.LockByCaller;
import quant.rich.emoney.interfaces.ConfigInfo;
import quant.rich.emoney.interfaces.IConfig;
import quant.rich.emoney.service.sqlite.RequestInfoService;
import quant.rich.emoney.util.SpringContextHolder;

/**
 * 指标信息配置，只做运行时管理，不做保存
 */
@Data
@Accessors(chain=true)
@Lazy(false)
@ConfigInfo(field = "indexInfo", name =" 指标信息配置", initDefault = true, managed = false)
public class IndexInfoConfig implements IConfig<IndexInfoConfig> {
    
    @JsonView(IConfig.Views.Persistence.class)
    private String configIndOnlineUrl;
    
    @JsonView(IConfig.Views.Persistence.class)
    private JsonNode configIndOnline;
    
    public IndexInfoConfig() {}
    
    public String getConfigIndOnlineStr() {
        return getConfigIndOnline().toPrettyString();
    }
    
    @LockByCaller
    @JsonIgnore
    public String getOnlineConfigByUrl(String url) throws IOException {
        synchronized (this) {
            if (SpringContextHolder.getBean(RequestInfoService.class).getDefaultRequestInfo() == null) {
                throw new RuntimeException("请先新增请求配置并作为默认配置");
            }
            Request request = new Request.Builder()
                    .url(url)
                    .header("Cache-Control", "no-cache")
                    .get()
                    .build();
    
            // 发出请求
            Response backendResponse = OkHttpClientProvider.getInstance().newCall(request).execute();
            if (backendResponse.body() != null) {
                // 将内容复制给前端
                return 
                    new String(backendResponse.body().bytes(), "UTF-8");
            } else {
                return "";
            }
        }
    }
 
}
