#! /usr/bin/env python
import datetime
import os
import sys

from scrib import barf, cfg

try:
	import redis
except:
	barf.Barf('ERR', 'Please install redis module for python.')
	sys.exit()


class Db:
	"""
	We need to support persistant connections instead of
	spamming the database with calls as we are doing now.
	"""
	def __init__(self):
		self.settings = cfg.set()
		# Don't set defaults here.
		self.settings.load('scrib.cfg', {}, suppress=True)
		self.barf = barf.Barf

		# Database vars
		self.host = self.settings.host
		self.port = self.settings.port
		self.tries = 0
		self.max_tries = 2
		self.prefix = 'scrib'  # Connect to Scrib Collective
		self.name = self.prefix  # Oh god why do I do this shit?!

		self.redis = self.check(self.host, self.port)

		self.path = os.path.expanduser('~') + '/.scrib/bots/' + self.name + '/logs/'
		if not os.path.exists(self.path):
			os.makedirs(self.path)

	def check(self, host='localhost', port='6379'):
		# Database check
		db = redis.Redis(host, port)
		# See if redis server is running
		try:
			ping = db.ping()
			if ping is not True:
				self.barf('ERR', 'No Redis server found.')
				self.barf('ERR', 'Please make sure your connection settings')
				self.barf('ERR', 'are correct and that target server is on.')
				sys.exit()
			else:
				if self.settings.debug is 1:
					self.barf('DBG', 'Connection to %s started' % host)
				return db
		except Exception as e:
			self.barf('ERR', e)
			self.tries += 1

		while self.tries < self.max_tries:
			self.check(self.settings.host, self.settings.port)
		else:
			self.barf('ERR', 'No redis server found.')
			self.barf('ACT', 'Please make sure it is started or your host is correct.')
			sys.exit()

	def info(self):
		"""
		db0 on ataraxia is Scrib Collective. It is also the default
		generated storage when one hosts their own server. This means
		that we are incompatible with siloing scrib to its own dbx
		until we make this more flexible.
		"""
		inf = self.redis.info('keyspace')
		return inf['db0']['keys']

	def add(self, key, words):
		"""
		Nicely wrap redis sadd
		"""
		if self.settings.debug is 1:
			self.barf('DBG', 'db.add: %s' % key)
		self.redis.sadd(self._make_key(key), words[-1])

	def get_random(self, key):
		if self.settings.debug is 1:
			self.barf('DBG', 'db.get_random: %s' % key)
		return self.redis.srandmember(self._make_key(key))

	def _make_key(self, k):
		if self.settings.debug is 1:
			self.barf('DBG', 'db._make_key fired.')
		return '-'.join((self.prefix, k))

	def log(self, payload):
		f = open(self.path + str(datetime.date.today()) + '.log', 'a')
		f.write(payload + '\n')
		f.close()
