package net.northking.cctp.testbug.api.service;

import net.northking.cctp.common.sequence.SequenceStorage;
import net.northking.cctp.testbug.db.entity.BugNo;
import net.northking.cctp.testbug.db.service.BugNoService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;

@Component
public class SequenceStorageImpl implements SequenceStorage {
    private final static Logger logger = LoggerFactory.getLogger(SequenceStorageImpl.class);
    @Autowired
    private BugNoService bugNoService;

    @Autowired
    private RedisLockRegistry redisLockRegistry;
    @Override
    public void save(String s, long l) {

    }

    @Override
    public Map<String, Long> findAll() {
        Map<String, Long> result = new HashMap<>();
        String redisKey = "test-bug-no-UPDATE";
        Lock lock = redisLockRegistry.obtain(redisKey);
        Boolean b = false;
        try {
            b = lock.tryLock();
            if (b) {
                //每次重启从列表中刷新编号最大值
                bugNoService.updateBugNo();
                List<BugNo> list = bugNoService.findAll();
                String suffix = "test-bug-no";
                String after  = "manualTest";
                for (BugNo cbn : list) {
                    String projectId = StringUtils.isEmpty(cbn.getProjectId())?"tenant":cbn.getProjectId();
                    String key = after+":"+ cbn.getTenantId() + ":"+ suffix +":"+ projectId + ":" + cbn.getNoType();
                    result.put(key,cbn.getNoValue());
                }
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        } finally {
            if (b) {
                lock.unlock();
            }
        }
        return result;
    }
}
