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

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;

/**
 * 〈一句话功能简述〉 〈功能详细描述〉
 *
 * @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;

    private static final String PREFIX = "CM_";

    @Override
    public void addKeyVal(final String key, final String value) {
        try {

            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;
                }
            });

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }

    }

    @Override
    public void deleteKey(final String key) {

        try {
            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;
                }
            });
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }

    }

    @Override
    public void addKeyValExpire(final String key, final String value, final long second) {
        try {
            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;
                }
            });
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }

    }

    @Override
    public Integer getIntegerByKey(final String key) {
        Integer returnValue = 0;
        try {
            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;
                }
            });
            if (val != null) {
                try {
                    returnValue = Integer.parseInt(val);
                } catch (Exception e) {
                    returnValue = 0;
                }
            }

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }

        return returnValue;
    }


    @Override
    public void increaseByKey(final String key) {
        try {
            redisTemplate.execute(new RedisCallback<Object>() {
                @Override
                public Object doInRedis(RedisConnection connection) throws DataAccessException {
                    byte[] serialKey = redisTemplate.getStringSerializer().serialize(PREFIX + key);
                    connection.incr(serialKey);
                    return null;
                }
            });
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    @Override
    public void decreaseByKey(final String key) {
        try {
            redisTemplate.execute(new RedisCallback<Object>() {
                @Override
                public Object doInRedis(RedisConnection connection) throws DataAccessException {
                    byte[] serialKey = redisTemplate.getStringSerializer().serialize(PREFIX + key);
                    connection.decr(serialKey);
                    return null;
                }
            });

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    @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(), e);
        }
    }

    @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(), e);
            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(), e);
        }
    }

    @Override
    public long getListSize(final String key) {
        long result = 0;
        try {
            result = redisTemplate.opsForList().size(PREFIX + key);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }

        return result;
    }

    @Override
    public String getValByKey(final String key) {
        String val = "";
        try {
            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;
                }
            });

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return val;
    }

    @Override
    public String getValByKeyNew(final String key) {
        String val = "";
        try {
            val = String.valueOf(redisTemplate.opsForValue().get(PREFIX + key));

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return val;
    }

    @Override
    public void setValueNew(final String key, final String value) {
        try {
            redisTemplate.opsForValue().set(PREFIX + key.trim(), value.trim());
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    @Override
    public void setValueExpireNew(final String key, final String value, final long expire) {
        try {
            redisTemplate.opsForValue().set(PREFIX + key.trim(), value.trim(), expire, TimeUnit.SECONDS);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

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

}
