/*
 * 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 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.io.Serializable;
import java.util.concurrent.TimeUnit;

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

    public static final String PREFIX = "HGS_";
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisUtils.class);
    @Autowired
    protected RedisTemplate<Serializable, Serializable> redisTemplate;

    @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 void addKeyObjectExpire(String key, final Object value, long second) {
        key = PREFIX + key;
        try {
            redisTemplate.opsForValue().set(key, (Serializable) value, second, TimeUnit.SECONDS);
        } catch (final Exception e) {
            LOGGER.error("Failed updating {}", e.getMessage());
        }
    }

    @Override
    public Object getObjectByKey(String key) {
        key = PREFIX + key;
        return redisTemplate.opsForValue().get(key);
    }

    @Override
    public String getValByKey(final String key) {
        return getValByKeyNew(key);
    }

    @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 boolean setNX(String key, String value, long seconds) {
        try {
            return lock(key,value,seconds);
        } catch (Exception ex) {
            LOGGER.error("查询定时任务key失败" + ex);
            return false;
        }
    }

    private boolean locked = false;

    private synchronized boolean lock(String lockKey,String value,long seconds){
        /*该方法会在没有key时，设置key;存在key时返回false；因此可以通过该方法及设置key的有效期，判断是否有其它线程持有锁*/
        Boolean success = redisTemplate.opsForValue().setIfAbsent(lockKey,value);
        if(success != null && success){
            redisTemplate.expire(lockKey,seconds,TimeUnit.SECONDS);
            locked = true;
        }else{
            locked = false;
        }
        return locked;
    }

}
