from rediscluster import RedisCluster
import redis, os
class RedisLib:

    def __init__(self):
        try:
            if int(os.getenv("REDIS_CLUSTER_ENABLED")) == 1:
                startup_nodes = [{"host": os.getenv("REDIS_CLUSTER_NODE_1_HOST"),
                                  "port": os.getenv("REDIS_CLUSTER_NODE_1_PORT")},
                                 {"host": os.getenv("REDIS_CLUSTER_NODE_2_HOST"),
                                  "port": os.getenv("REDIS_CLUSTER_NODE_2_PORT")},
                                 {"host": os.getenv("REDIS_CLUSTER_NODE_3_HOST"),
                                  "port": os.getenv("REDIS_CLUSTER_NODE_3_PORT")},
                                 {"host": os.getenv("REDIS_CLUSTER_NODE_4_HOST"),
                                  "port": os.getenv("REDIS_CLUSTER_NODE_4_PORT")},
                                 {"host": os.getenv("REDIS_CLUSTER_NODE_5_HOST"),
                                  "port": os.getenv("REDIS_CLUSTER_NODE_5_PORT")},
                                 {"host": os.getenv("REDIS_CLUSTER_NODE_6_HOST"),
                                  "port": os.getenv("REDIS_CLUSTER_NODE_6_PORT")}]
                self.RedisConn = RedisCluster(startup_nodes=startup_nodes, decode_responses=True,
                                              password=os.getenv("REDIS_CLUSTER_PASSWORD"))
            elif int(os.getenv("REDIS_ENABLED")) == 1:
                self.RedisConn = redis.Redis(password=os.getenv("REDIS_PASSWORD"), host=os.getenv("REDIS_HOST"), port=int(os.getenv("REDIS_PORT")), db=0, charset="utf-8", decode_responses=True)
                # charset="utf-8", decode_responses=True added in order to return as str instead of byte.
        except Exception as e:
            print(str(e))
            self.RedisConn =False
            return None

    def is_redis_available(self):
        try:
            if int(os.getenv("REDIS_CLUSTER_ENABLED")) == 1 or int(os.getenv("REDIS_ENABLED")) == 1:
                return True

            return False
        except Exception as e:
            return False

    def get(self, key):
        if self.is_redis_available():
            return self.RedisConn.get(key)
        return False

    def remove(self, key):
        if self.is_redis_available():
            return self.RedisConn.delete(key)
        return False

    def set(self, key, value, ex=None):
        if self.is_redis_available():
            return self.RedisConn.set(key, value, ex)
        return False

    def scan(self, key):
        if self.is_redis_available():
            return self.RedisConn.scan_iter("*" + key + "*")
        return False
