package com.yutou.bilibili.Tools;

import com.alibaba.fastjson.JSONObject;
import com.yutou.bilibili.QQBot.QQBotManager;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisPubSub;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.Set;


public class RedisTools {
    private static boolean isNotInstallRedis = false;
    private static String host;
    private static int port;
    public static int TOKEN_TIMEOUT_DEFAULT = 360;

    private RedisTools() {

    }

    // 写成静态代码块形式，只加载一次，节省资源
    static {
        //Properties properties = PropertyUtil.loadProperties("jedis.properties");
        //host = properties.getProperty("redis.host");
        //port = Integer.valueOf(properties.getProperty("redis.port"));
        host = "127.0.0.1";
        port = 6379;
    }

    public static boolean set(int dbIndex, String key, String value) {
        try {
            if (isNotInstallRedis) {
                return false;
            }
            Jedis jedis = getRedis();
            jedis.select(dbIndex);
            String ret = jedis.set(key, value);
            jedis.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static boolean set(String key, String value) {
        return set(0, key, value);
    }

    public static boolean set(String key, String value, int timeout) {
        try {
            if (isNotInstallRedis) {
                return false;
            }
            Jedis jedis = getRedis();
            if (timeout == -1) {
                jedis.set(key, value);
            } else {
                jedis.setex(key, timeout, value);
            }
            jedis.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static String get(String key, int dbIndex) {
        String value = "-999";
        if (isNotInstallRedis) {
            return value;
        }
        try (Jedis jedis = getRedis()) {
            jedis.select(dbIndex);
            value = jedis.get(key);
            jedis.close();
        } catch (Exception e) {
            // TODO: handle exception
            //	e.printStackTrace();
        }
        return value;
    }

    public static String get(String key) {
        return get(key, 0);
    }

    public static boolean remove(String key) {
       return remove(key,0);
    }

    public static void removeLoginState(String uid) {
        Jedis jedis = getRedis();
        Set<String> keys = jedis.keys("*");
        for (String string : keys) {
            if (string.equals(uid)) {
                jedis.del(string);
            }
        }

    }

    public static String ping() {
        Jedis jedis = getRedis();
        String tmp = jedis.ping();
        jedis.close();
        return tmp;
    }

    public static boolean exists(String key, String value) {
        if (isNotInstallRedis) {
            return false;
        }
        Jedis jedis = getRedis();
        boolean flag = value.equals(jedis.get(key));
        jedis.close();
        return flag;
    }

    public static Jedis getRedis() {
        return new Jedis(host, port);
    }

    public static boolean remove(String key, int index) {
        if (isNotInstallRedis) {
            return false;
        }
        Jedis jedis = getRedis();
        jedis.select(index);
        Long i = jedis.del(key);
        jedis.close();
        if (i > 0) {
            return true;
        } else {
            return false;
        }
    }

    private static class PropertyUtil {

        // 加载property文件到io流里面
        public static Properties loadProperties(String propertyFile) {
            Properties properties = new Properties();
            try {
                InputStream is = PropertyUtil.class.getClassLoader().getResourceAsStream(propertyFile);
                if (is == null) {
                    is = PropertyUtil.class.getClassLoader().getResourceAsStream(propertyFile);
                }
                properties.load(is);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return properties;
        }
    }

    private static Jedis getPoolRedis() {
        if (isNotInstallRedis) {
            return null;
        }
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(0);
        poolConfig.setMaxWaitMillis(1000);
        JedisPool pool = new JedisPool(poolConfig, host);
        return pool.getResource();
    }

    public static void pullMsg(String channel, String msg) {
        Jedis jedis = getPoolRedis();
        jedis.publish(channel, msg);
        jedis.close();
    }

    private static boolean init = false;

    public static void initRedisPoolSub() {
        if (init)
            return;
        init = true;
       Log.i("初始化订阅");
        new Thread(new Runnable() {
            @Override
            public void run() {
                Jedis jedis = getPoolRedis();
                if (jedis != null)
                    jedis.psubscribe(new Consumer(), "*");
            }
        }).start();

    }

    protected static class Consumer extends JedisPubSub {
        @Override
        public void onPMessage(String pattern, String channel, String message) {
            super.onPMessage(pattern, channel, message);
           Log.i("onPMessage: channel=" + channel + " msg=" + message + " pattern=" + pattern);
            switch (channel) {
                case "bot":
                    bot(message);
                    break;
            }
        }

        @Override
        public void onMessage(String channel, String message) {
            super.onMessage(channel, message);
           Log.i("onMessage: channel=" + channel + " msg=" + message);
        }




        public static void bot(String value) {
            switch (value) {
                case "getip":
                    JSONObject json = JSONObject.parseObject(HttpTools.get("https://api.asilu.com/ip/"));
                    String ip = json.getString("ip");
                    QQBotManager.getInstance().sendMessage("服务器IP:\n" + ip);
                    break;
            }
        }
    }
    public static void main(String[] args) {
        RedisTools.pullMsg("msg", "abc");
    }
}
