/*
 * Copyright (C), 2002-2015, 365
 * FileName: //文件名
 * Author:   Administrator
 * Date:     2015年11月4日 上午10:17:41
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.house365.ws.cached;

import com.google.common.base.Strings;
import com.house365.web.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
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.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Transaction;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 〈一句话功能简述〉 〈功能详细描述〉
 *
 * @author hqc
 */
@Component("redisUtils")
@Scope("prototype")
public class RedisUtils implements RedisUtilsInterface {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisUtils.class);

    @Autowired
    protected RedisTemplate<Serializable, Serializable> redisTemplate;

    public static final String PREFIX = "CM_";

    @Override
    public void addKeyVal(final String key, final String value) {
        redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] serialKey = redisTemplate.getStringSerializer().serialize(PREFIX + key);
                connection.del(serialKey);
                connection.set(serialKey, redisTemplate.getStringSerializer().serialize(value));
                return null;
            }
        });
        LOGGER.debug("【添加缓存消息】key=" + key + "   value=" + value);
    }

    @Override
    public void deleteKey(final String key) {
        redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] serialKey = redisTemplate.getStringSerializer().serialize(PREFIX + key);
                connection.del(serialKey);
                return null;
            }
        });
        LOGGER.debug("【删除】key=" + key);
    }

    @Override
    public void addKeyValExpire(
        final String key, final String value, final long second
    ) {
        redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] serialKey = redisTemplate.getStringSerializer().serialize(PREFIX + key);
                connection.del(serialKey);
                connection.set(serialKey, redisTemplate.getStringSerializer().serialize(value));
                connection.expire(serialKey, second);
                return null;
            }
        });
        LOGGER.debug("【添加缓存消息】key=" + key + "  second=" + second + "   value=" + value);
    }

    @Override
    public String getValByKey(final String key) {
        String val = redisTemplate.execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] keySeril = redisTemplate.getStringSerializer().serialize(PREFIX + key);
                if (connection.exists(keySeril)) {
                    byte[] val = connection.get(keySeril);
                    String valDeserial = redisTemplate.getStringSerializer().deserialize(val);
                    return valDeserial;
                }
                return null;
            }
        });
        LOGGER.debug("【获取缓存消息】key=" + key + "   value=" + val);
        return val;
    }

    @Override
    public String getValByKeyNew(final String key) {
        String val = String.valueOf(redisTemplate.opsForValue().get(PREFIX + key));
        LOGGER.debug("【获取缓存消息】key=" + key + "   value=" + val);
        return val;
    }

    @Override
    public Integer getIntegerByKey(final String key) {
        String val = redisTemplate.execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] keySeril = redisTemplate.getStringSerializer().serialize(PREFIX + key);
                if (connection.exists(keySeril)) {
                    byte[] val = connection.get(keySeril);
                    String valDeserial = redisTemplate.getStringSerializer().deserialize(val);
                    return valDeserial;
                }
                return null;
            }
        });
        LOGGER.debug("【获取缓存消息】key=" + key + "   value=" + val);
        Integer returnValue = 0;
        if (val != null) {
            try {
                returnValue = Integer.parseInt(val);
            } catch (Exception e) {
                returnValue = 0;
            }
        }
        return returnValue;
    }

    @Override
    public Long increaseByKey(final String key) {
        Object obj = redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] serialKey = redisTemplate.getStringSerializer().serialize(PREFIX + key);
                return connection.incr(serialKey);
            }
        });
        LOGGER.debug("【加1】key=" + key);
        if (obj != null) {
            return (Long) obj;
        } else {
            return null;
        }
    }

    @Override
    public Long decreaseByKey(final String key) {
        Object obj = redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] serialKey = redisTemplate.getStringSerializer().serialize(PREFIX + key);
                return connection.decr(serialKey);
            }
        });
        LOGGER.debug("【加1】key=" + key);
        if (obj != null) {
            return (Long) obj;
        } else {
            return null;
        }
    }

    @Override
    public void pushIntegerIntoRedisList(final String key, final Integer value) {
        try {
            redisTemplate.execute(new RedisCallback<Object>() {
                @Override
                public Object doInRedis(RedisConnection connection) throws DataAccessException {
                    byte[] serialKey = redisTemplate.getStringSerializer().serialize(PREFIX + key);
                    connection.lPush(serialKey, redisTemplate.getStringSerializer().serialize(String.valueOf(value)));
                    return null;
                }
            });
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
        LOGGER.debug("insert " + key + " log into redis:" + value);
    }

    @Override
    public Integer popIntegerFromRedisList(final String key) {
        try {
            Object obj = redisTemplate.execute(new RedisCallback<Object>() {
                @Override
                public Object doInRedis(RedisConnection connection) throws DataAccessException {
                    byte[] serialKey = redisTemplate.getStringSerializer().serialize(PREFIX + key);
                    byte[] result = connection.lPop(serialKey);
                    if (result == null) {
                        return null;
                    }
                    return redisTemplate.getStringSerializer().deserialize(result);
                }
            });
            LOGGER.debug("pop Integer from list :" + key);
            if (obj != null) {
                return Integer.parseInt(String.valueOf(obj));
            } else {
                return null;
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return null;
        }
    }

    @Override
    public void removeRedisList(final String key) {
        try {
            redisTemplate.execute(new RedisCallback<Object>() {
                @Override
                public Object doInRedis(RedisConnection connection) throws DataAccessException {
                    byte[] serialKey = redisTemplate.getStringSerializer().serialize(PREFIX + key);
                    redisTemplate.delete(serialKey);
                    return null;
                }
            });
            LOGGER.debug("remove list Integer from list :" + key);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
    }

    @Override
    public long getListSize(final String key) {
        return redisTemplate.opsForList().size(PREFIX + key);
    }

    @Override
    public String getSet(final String key, final String value) {
        return String.valueOf(redisTemplate.opsForValue().getAndSet(PREFIX + key.trim(), value.trim()));
    }

    @Override
    public boolean setNotExists(final String key, final String value) {
        return redisTemplate.opsForValue().setIfAbsent(PREFIX + key.trim(), value.trim());
    }

    @Override
    public boolean hasKey(final String key) {
        return redisTemplate.hasKey(PREFIX + key.trim());
    }

    @Override
    public void setValueNew(final String key, final String value) {
        if (!Strings.isNullOrEmpty(key) && !Strings.isNullOrEmpty(value)) {
            redisTemplate.opsForValue().set(PREFIX + key.trim(), value.trim());
        }
    }

    @Override
    public void setValueExpireNew(final String key, final String value, final long expire, TimeUnit timeUnit) {
        if (!Strings.isNullOrEmpty(key) && !Strings.isNullOrEmpty(value)) {
            redisTemplate.opsForValue().set(PREFIX + key.trim(), value.trim(), expire, timeUnit);
        }
    }

    @Override
    public void deleteByKeyNew(final String key) {
        if (!Strings.isNullOrEmpty(key)) {
            redisTemplate.delete(PREFIX + key);
        }
    }

    @Override
    public void setAdd(final String key, final String value) {
        if (!Strings.isNullOrEmpty(key) && !Strings.isNullOrEmpty(value)) {
            redisTemplate.opsForSet().add(PREFIX + key, value);
        }
    }

    @Override
    public void setRemove(final String key, final String value) {
        if (!Strings.isNullOrEmpty(key) && !Strings.isNullOrEmpty(value)) {
            redisTemplate.opsForSet().remove(PREFIX + key, value);
        }
    }

    @Override
    public boolean isSetMember(final String key, final String value) {
        boolean flag = false;
        if (!Strings.isNullOrEmpty(key) && !Strings.isNullOrEmpty(value)) {
            flag = redisTemplate.opsForSet().isMember(PREFIX + key, value);
        }
        return flag;
    }

    @Override
    public Set<Serializable> getSetMember(final String key) {
        Set<Serializable> flag = new HashSet<>();
        if (!Strings.isNullOrEmpty(key)) {
            flag = redisTemplate.opsForSet().members(PREFIX + key);
        }
        return flag;
    }

}
