package com.reyun.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
/**
 * 单节点Jedis.
 * @author Administrator
 *
 */
public class RedisUtilNew {
	protected static Logger logger = LoggerFactory.getLogger(RedisUtilNew.class);
	private static RedisUtilNew redisUtil = new RedisUtilNew();
	private JedisPool pool;

	//
	// private ResourceBundle resourceBundle;

	private RedisUtilNew() {
		ResourceBundle resourceBundle = ResourceBundle.getBundle("redis");
		pool = new JedisPool(resourceBundle.getString("redis.surl.host"),
				Integer.valueOf(resourceBundle.getString("redis.surl.port")));
	}

	public static RedisUtilNew getInstance() {
		return redisUtil;
	}
	
	public Map<String, String> hgetAll(String key) {
		Map<String, String> result = new HashMap<String, String>();
		
		Jedis jedis = pool.getResource();
		result = jedis.hgetAll(key);
		pool.returnResource(jedis);
		
		return result;
	}

	public void hsetAll(String key, Map<String, String> map) {
		Jedis jedis = pool.getResource();
		jedis.hmset(key, map);
		pool.returnResource(jedis);
	}
	
	public void delete(String key) {
		Jedis jedis = pool.getResource();
		jedis.del(key);
		pool.returnResource(jedis);
	}

	/**
	 * 取值
	 *
	 * @param key
	 * @return
	 */
	public String get(String key) {
		Jedis jedis = pool.getResource();
		try {
			String result = jedis.get(key);
			if (result == null) {
				return null;
			}
			return result;
		} finally {
			pool.returnResource(jedis);
		}
	}

	/**
	 * 向redis中写入数据
	 * @param key
	 * @param value
	 */
	public void set(String key,String value)
	{
		Jedis jedis = pool.getResource();
		jedis.set(key,value);
		pool.returnResource(jedis);
	}

	public Long getExpireTime(String key)
	{
		Jedis jedis = pool.getResource();
		Long m = jedis.ttl(key);
        pool.returnResource(jedis);
		return m;
	}


	/**
	 * 加锁.
	 *
	 * @param key
	 * @param expireTime
	 *            超时时间单位秒.
	 * @return 锁定的value,返回null值加锁失败,供释放锁时使用.
	 */
	public String tryLock(String key, int expireTime) {
		Jedis jedis = pool.getResource();
		try {
			String value = Long.toString(System.currentTimeMillis() + (expireTime * 1000));
			String result = jedis.set(key, value, "NX", "EX", expireTime);
			if (result == null) {
				return null;
			}
			return value;
		} finally {
			pool.returnResource(jedis);
		}
	}

	public String expireValue(String key, String value, int expireTime)
	{
		Jedis jedis = pool.getResource();
		try {
			String result = jedis.set(key, value, "NX", "EX", expireTime);
			if (result == null) {
				return null;
			}
			return value;
		} finally {
			pool.returnResource(jedis);
		}
	}

	public void releaseLock(String key) {
		Jedis jedis = pool.getResource();
		try {
			Set<String> set = jedis.keys(key);
			String[] kk = new String[set.size()];
			jedis.del(set.toArray(kk));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.returnResource(jedis);
		}
	}
	
	public static List<Map<String, String>> query4redis() throws SQLException {
		DBUtil dbUtil = DBUtil.newInstance();
		String sql = "select c.channel, c.channelid,c.name,c.url,c.special_keys,c.surl,c.campaignpackid, a.appkey,a.url as appurl,ch.name as channelname,ch.unique_name,ch.category as category, c.campaign_group as gid from campaign c, app a, channel ch where  a.id=c.app and ch.id=c.channel and c.surl not like 'jump%'";
		Connection conn = dbUtil.getConn();
		Statement st = conn.createStatement();
		ResultSet rs = st.executeQuery(sql);
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		while (rs.next()) {
			String surl = rs.getString("surl");
			Map<String, String> inner = new HashMap<String, String>();
			
			inner.put("name", rs.getString("name"));
			inner.put("channelid", rs.getString("channelid"));
			String uniq = rs.getString("unique_name");
			inner.put("channelname", StringUtil.isEmpty(uniq) ? "" : uniq);
			inner.put("channel", rs.getString("channelname"));
			inner.put("cid", rs.getString("channel"));
			inner.put("appid", rs.getString("appkey"));
			String special = rs.getString("special_keys");
			if (!StringUtil.isEmpty(special)) {
				inner.put("specialkeys", special);
			}
			String appurl = rs.getString("appurl");
			String url = rs.getString("url");
			inner.put("url", StringUtil.isEmpty(url) ? appurl : url);
			String category = rs.getString("category");
			inner.put("category", category);
			String campaignpackid = rs.getString("campaignpackid");
			if (!StringUtil.isEmpty(category) && category.equals("APPMARKET")) {
				surl = rs.getString("appkey")+":"+campaignpackid;
			}
			inner.put("surl", surl);
			inner.put("gid", rs.getString("gid"));
			
			list.add(inner);
		}
		if (rs != null) {
			rs.close();
		}
		if (st != null) {
			rs.close();
		}
		if (conn != null) {
			conn.close();
		}
		return list;
	}

	public static void main(String[] args) {

		RedisUtilNew redisUtilNew = RedisUtilNew.getInstance();

		//redisUtilNew.expireValue("test005","12",1000);

		Long outtime = redisUtilNew.getExpireTime("test005");

		redisUtilNew.delete("test005");

		redisUtilNew.expireValue("test005","12",outtime.intValue());



		System.out.println(outtime);
	}

}
