#!/usr/bin/python2
"""
initialize the redis databases and create and store a random maze recursively
"""
import redis
import random
import sys
import math

global gMaze, sx, sy, it
gMaze = []
maxX = 6
maxY = 6
sx = 6
sy = 6
it = 0

sys.setrecursionlimit( 2000)

db_MazeLayout = 0
db_Entities = 1

random.seed()

for i in range( 0, maxX*maxY):
    gMaze.append({0:'w',1:'w',2:'w',3:'w','visited':False})


def recurse(x, y):
    global gMaze, sy, sy, it
    print "iteration: "+str(it)+" Room @ "+str(x)+" : "+str(y)
    it = it + 1
    gMaze[(y*sx) + x]['visited'] = True
    seq = [0,1,2,3]
    random.shuffle( seq)
    for i in range(0,4):
        neighbour = seq[i]
        if neighbour == 0:
            nx = x
            ny = y-1
            if ny < 0 or gMaze[(ny*sx) + nx]['visited']:
                continue        
            else:
                gMaze[(y*sx) + x][0] = 'd'
                gMaze[(ny*sx) + nx][2] = 'd'
                recurse(x, ny)
        elif neighbour == 1:
            nx = x+1
            ny = y
            if nx >= sx or gMaze[(ny*sx) + nx]['visited']:
                continue
            else:
                gMaze[(y*sx) + x][1] = 'd'
                gMaze[(ny*sx) + nx][3] = 'd'
                recurse(nx, y)
        elif neighbour == 2:
            nx = x
            ny = y+1
            if ny >= sy or gMaze[(ny*sx) + x]['visited']:
                continue                    
            else:
                gMaze[(y*sx) + x][2] = 'd'
                gMaze[(ny*sx) + nx][0] = 'd'
                recurse(x, ny)
        elif neighbour == 3:
            nx = x-1
            ny = y
            if nx < 0 or gMaze[(ny*sx) + nx]['visited']:
                continue
            else:
                gMaze[(y*sx) + x][3] = 'd'
                gMaze[(ny*sx) + nx][1] = 'd'
                recurse(nx,y)
    
def createStoreMaze():
    global gMaze, sx, sy
    recurse( 0,0)
    r = redis.StrictRedis( host='localhost', port=6379, db=db_Entities)
    r.flushdb()
    r = redis.StrictRedis( host='localhost', port=6379, db=db_MazeLayout)
    r.flushdb()
    for i in range( 0, sy):
        for s in range( 0, sx):
            items=""
            if  s==(sx-1) and i==(sy-1):
                items = "stairs"        
            data = {'walls':( gMaze[(i*sx)+s][0], gMaze[(i*sx)+s][1], gMaze[(i*sx)+s][2], gMaze[(i*sx)+s][3]), 'entities':[], 'items':[items], 'grafiti':""};
            k = "x"+str(s)+"y"+str(i)
            r.set( k, data)

    print "\ndone\n"
    
createStoreMaze();


