package com.ycwl.basic.repository;

import com.ycwl.basic.utils.JacksonUtil;
import com.ycwl.basic.mapper.FaceMapper;
import com.ycwl.basic.mapper.FaceSampleMapper;
import com.ycwl.basic.model.pc.face.entity.FaceEntity;
import com.ycwl.basic.model.pc.faceSample.entity.FaceSampleEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class FaceRepository {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private FaceMapper faceMapper;
    @Autowired
    private FaceSampleMapper faceSampleMapper;

    public static final String FACE_CACHE_KEY = "face:%s";
    public static final String FACE_SAMPLE_CACHE_KEY = "face:sample:%s";

    public FaceEntity getFace(Long id) {
        if (redisTemplate.hasKey(String.format(FACE_CACHE_KEY, id))) {
            String json = redisTemplate.opsForValue().get(String.format(FACE_CACHE_KEY, id));
            if (json == null) {
                return null;
            }
            return JacksonUtil.parseObject(json, FaceEntity.class);
        }
        FaceEntity face = faceMapper.get(id);
        if (face != null) {
            redisTemplate.opsForValue().set(String.format(FACE_CACHE_KEY, id), JacksonUtil.toJSONString(face), 12, TimeUnit.HOURS);
        }
        return face;
    }

    public List<FaceSampleEntity> getFaceSampleList(Long faceId) {
        FaceEntity face = getFace(faceId);
        if (face == null) {
            return Collections.emptyList();
        }
        if (StringUtils.isBlank(face.getMatchSampleIds())) {
            return Collections.emptyList();
        }
        List<FaceSampleEntity> list = faceSampleMapper.listByIds(Arrays.stream(face.getMatchSampleIds().split(",")).map(Long::valueOf).collect(Collectors.toList()));
        return list;
    }

    public void clearFaceCache(Long faceId) {
        redisTemplate.delete(String.format(FACE_CACHE_KEY, faceId));
        redisTemplate.delete(String.format(FACE_SAMPLE_CACHE_KEY, faceId));
    }

    public FaceSampleEntity getFaceSample(Long faceSampleId) {
        return faceSampleMapper.getEntity(faceSampleId);
    }
}
