package com.diagbot.service.impl;

import com.diagbot.service.ColumnService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Service
public class ColumnServiceImpl implements ColumnService {
    @Autowired
    @Qualifier("redisTemplateForTable")
    RedisTemplate redisForTable;

    private byte[] serializeKey(Object o) {
        return redisForTable.getKeySerializer().serialize(o);
    }

    private byte[] serializeValue(Object o) {
        return redisForTable.getValueSerializer().serialize(o);
    }

    private Object deserializeValue(byte[] b) {
        return redisForTable.getValueSerializer().deserialize(b);
    }

    @Override
    public Boolean createColumn(Map<String, String> columnMap, String tableResKey) {
        final byte[] redis_key = serializeKey(tableResKey);
        redisForTable.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                //获取旧的
                byte[] bytes = connection.get(redis_key);
                //删除旧的
                if (bytes != null) {
                    connection.del(bytes);
                }
                //设置新的
                connection.setNX(redis_key,serializeValue(columnMap));
                return true;
            }
        });
        return true;
    }

    @Override
    public Map<String, String> getColumn(String tableResKey) {
        final byte[] redis_key =serializeKey(tableResKey);
        Map<String, String> columnMap=(Map<String, String>)redisForTable.execute(new RedisCallback<Map<String, String>>() {
            @Override
            public Map<String, String> doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] bytes = connection.get(redis_key);
                if (bytes == null) {
                    return null;
                }
                return (Map<String, String>) deserializeValue(bytes);
            }
        });
        /*list.forEach(s->{
            s.setEn(NamingStrategy.underlineToCamel(s.getEn()));
        });
        Map<String, String> columnMap= EntityUtil.makeMapWithKeyValue(list,"ch","en");*/
        return columnMap;
    }
}
