package com.tzld.piaoquan.recommend.server.remote;

import com.tzld.piaoquan.recommend.feature.client.FeatureV2Client;
import com.tzld.piaoquan.recommend.feature.model.feature.FeatureKeyProto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;


/**
 * @author dyp
 */
@Component
@Slf4j
public class FeatureV2RemoteService {

    private static final int INFO_LOG_PROTO_THRESHOLD = 500;
    private static final long INFO_LOG_COST_THRESHOLD_MS = 200L;

    @Autowired
    private FeatureV2Client client;

    public Map<String, String> getFeature(List<FeatureKeyProto> protos) {
        if (CollectionUtils.isEmpty(protos)) {
            return Collections.emptyMap();
        }
        try {
            long start = System.currentTimeMillis();
            Map<String, String> result = client.multiGetFeature(protos);
            int resultSize = result != null ? result.size() : 0;
            long costTime = System.currentTimeMillis() - start;
            if (protos.size() > INFO_LOG_PROTO_THRESHOLD
                    || costTime > INFO_LOG_COST_THRESHOLD_MS
                    || resultSize == 0) {
                log.info("FeatureV2RemoteService.getFeature: protos.size={}, result.size={}, costTime={}",
                        protos.size(), resultSize, costTime);
            }
            return result != null ? result : Collections.emptyMap();
        } catch (Exception e) {
            log.error("FeatureV2RemoteService.getFeature: unexpected exception, protos.size={}", protos.size(), e);
            return Collections.emptyMap();
        }
    }


}
