# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals

import redis, frappe, cPickle as pickle

class RedisWrapper(redis.Redis):
	"""Redis client that will automatically prefix conf.db_name"""
	def make_key(self, key, user=None):
		if user:
			if user == True:
				user = frappe.session.user

			key = "user:{0}:{1}".format(user, key)

		return (frappe.conf.db_name + "|" + key).encode('utf-8')

	def set_value(self, key, val, user=None):
		"""Sets cache value."""
		key = self.make_key(key, user)
		frappe.local.cache[key] = val
		self.set(key, pickle.dumps(val))

	def get_value(self, key, generator=None, user=None):
		"""Returns cache value. If not found and generator function is
			given, it will call the generator.

		:param key: Cache key.
		:param generator: Function to be called to generate a value if `None` is returned."""
		original_key = key
		key = self.make_key(key, user)
		val = frappe.local.cache.get(key)
		if val is None:
			val = self.get(key)
			if val is not None:
				val = pickle.loads(val)
			if val is None and generator:
				val = generator()
				self.set_value(original_key, val, user=user)
			else:
				frappe.local.cache[key] = val
		return val

	def get_all(self, key):
		ret = {}
		for k in self.get_keys(key):
			ret[key] = self.get_value(k)

		return ret

	def get_keys(self, key):
		"""Return keys with wildcard `*`."""
		return self.keys(self.make_key(key + "*"))

	def delete_keys(self, key):
		"""Delete keys with wildcard `*`."""
		self.delete_value(self.get_keys(key), make_keys=False)

	def delete_value(self, keys, user=None, make_keys=True):
		"""Delete value, list of values."""
		if not isinstance(keys, (list, tuple)):
			keys = (keys, )

		for key in keys:
			if make_keys:
				key = self.make_key(key)

			self.delete(key)
			if key in frappe.local.cache:
				del frappe.local.cache[key]

@@ -612,16 +612,24 @@
 %5D = val%0A
+%09%09try:%0A%09
 %09%09self.s
@@ -654,16 +654,74 @@
 ps(val))
+%0A%09%09except redis.exceptions.ConnectionError:%0A%09%09%09return None
 %0A%0A%09def g
@@ -1093,16 +1093,25 @@
 s None:%0A
+%09%09%09try:%0A%09
 %09%09%09val =
@@ -1121,24 +1121,77 @@
 lf.get(key)%0A
+%09%09%09except redis.exceptions.ConnectionError:%0A%09%09%09%09pass%0A
 %09%09%09if val is
@@ -1569,16 +1569,24 @@
 %60*%60.%22%22%22%0A
+%09%09try:%0A%09
 %09%09return
@@ -1621,16 +1621,72 @@
  + %22*%22))
+%0A%09%09except redis.exceptions.ConnectionError:%0A%09%09%09return %5B%5D
 %0A%0A%09def d
@@ -1747,16 +1747,24 @@
 %60*%60.%22%22%22%0A
+%09%09try:%0A%09
 %09%09self.d
@@ -1811,16 +1811,67 @@
 s=False)
+%0A%09%09except redis.exceptions.ConnectionError:%0A%09%09%09pass
 %0A%0A%09def d
@@ -2088,16 +2088,25 @@
 y(key)%0A%0A
+%09%09%09try:%0A%09
 %09%09%09self.
@@ -2117,16 +2117,70 @@
 te(key)%0A
+%09%09%09except redis.exceptions.ConnectionError:%0A%09%09%09%09pass%0A%0A
 %09%09%09if ke

make caching work if redis not running