import redis
from redis.sentinel import Sentinel
import time
class connectNeon():   
    def __init__(self, ip_port, passwd, timeout):        
        self.status=False
        self.redisWrite=None
        self.redisRead=None
        begin=time.time()
        while True:
            if not self.redisWrite:
                #self.server = redis.Redis(host=ip, port=port, password=passwd, db=0, socket_connect_timeout=1.0)
                sentinel = Sentinel(ip_port, socket_timeout=10)
                try:
                    self.redisRead=sentinel.slave_for('neonmaster', socket_timeout=30, password=passwd)
                    self.redisWrite=sentinel.master_for('neonmaster', socket_timeout=30, password=passwd)
                except (redis.exceptions.ConnectionError):
                    print 'ERROR: Redis falied'
                if self.redisWrite is not None:
                    if self.redisRead is None: self.redisRead=self.redisWrite
                    self.status = True
                    print 'INFO: Redis connected'
                    break
                else:
                    print 'ERROR: Redis falied'
                if time.time()-begin>timeout:
                    print 'WARNING: Reids timeout'
                    break   

    def getStatus(self):
        return self.status   

    def getRedisWrite(self):
        return self.redisWrite

    def getRedisRead(self):
        return self.redisRead
