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

import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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 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<String, Object> redisTemplate;

    private static final String PREFIX = "HGS_";
    //1122

    @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 Object getObjectByKey(String key) {
        key = PREFIX + key;
        return redisTemplate.opsForValue().get(key);
    }

    @Override
    public void addKeyObjectExpire(String key, final Object value, long second) {
        key = PREFIX + key;
        try {
            redisTemplate.opsForValue().set(key, value, second, TimeUnit.SECONDS);
        } catch (final Exception e) {
            LOGGER.error("Failed updating {}", e.getMessage());
        }
    }

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

    @Override
    public Set<String> keys(String keyPattern) {
        Set<String> keys = redisTemplate.keys(keyPattern);
        return keys;
    }

    @Override
    public void removeKeys(Set<String> keys) {
        redisTemplate.delete(PREFIX + keys);
    }


    @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 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.toString());
                    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 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);
        }
    }
}
