'''
Created on Jun 18, 2012

@author: jacob.bennett
'''
from tables import *
from numpy import *
import Queue
import datetime
import threading
import time
import TimeHandler

dicts = Queue.Queue()
openFi = None
openFiBuffer = None
currentDate = None
notset = True
multiInstances = False
lock = threading.Lock()

class Tick(IsDescription):
    primaryTime = UInt32Col()
    secondaryTime = UInt32Col()
    side = UInt16Col()
    level = UInt16Col()
    price = UInt64Col()
    quant = UInt64Col()
    orders = UInt16Col()
    
#def updateBook(instrument, timestamp, side, level, price, quant, orders, monthyear, day):
#    global group
#    if day != currentDayOfMonth:
#        currentDayOfMonth = day
#        group = file.createGroup("/", "day" + str(day), 'Day of Month')
#    try:
#        table = file.getNode("/day" + str(day), "tick" + str(instrument))
#    except (NoSuchNodeError):
#        table = file.createTable(group, "tick" + str(instrument), Tick, str(instrument) + "Tick")
#        #table.cols.timestamp.createIndex()
#    table.row['timestamp'] = timestamp
#    table.row['side'] = side
#    table.row['level'] = level
#    table.row['price'] = price
#    table.row['quant'] = quant
#    table.row['orders'] = orders
#    table.row.append()
#    table.flush()
#    file.flush()
#    return

def acceptDict():
    while True:
        while not dicts.empty():
            lock.acquire()
            dictInst = dicts.get()
            for mainTuple, dataArray in dictInst.iteritems():
                if not(multiInstances):
                    try:
                        tableD = openFi.getNode("/" + mainTuple[1] + "/s" + str(mainTuple[2]) + "/t" + str(mainTuple[0]))
                    except(NoSuchNodeError):
                        try:
                            group2 = openFi.getNode("/" + mainTuple[1] + "/s" + str(mainTuple[2]))
                        except(NoSuchNodeError):
                            try:
                                group1 = openFi.getNode("/" + mainTuple[1])
                            except(NoSuchNodeError):
                                group1 = openFi.createGroup("/", mainTuple[1], mainTuple[1])
                            group2 = openFi.createGroup(group1, "s" + str(mainTuple[2]), str(mainTuple[2]))
                        tableD = openFi.createTable(group2, "t" + str(mainTuple[0]), Tick, "Instrument")
                    tableD.append(dataArray)
                    tableD.flush()
                else:
                    if mainTuple[3] != TimeHandler.getYearMonthDay(currentDate):
                        try:
                            tableD = openFiBuffer.getNode("/" + mainTuple[1] + "/s" + str(mainTuple[2]) + "/t" + str(mainTuple[0]))
                        except(NoSuchNodeError):
                            try:
                                group2 = openFiBuffer.getNode("/" + mainTuple[1] + "/s" + str(mainTuple[2]))
                            except(NoSuchNodeError):
                                try:
                                    group1 = openFiBuffer.getNode("/" + mainTuple[1])
                                except(NoSuchNodeError):
                                    group1 = openFiBuffer.createGroup("/", mainTuple[1], mainTuple[1])
                                group2 = openFiBuffer.createGroup(group1, "s" + str(mainTuple[2]), str(mainTuple[2]))
                            tableD = openFiBuffer.createTable(group2, "t" + str(mainTuple[0]), Tick, "Instrument")
                        tableD.append(dataArray)
                        tableD.flush()
                    else:
                        try:
                            tableD = openFi.getNode("/" + mainTuple[1] + "/s" + str(mainTuple[2]) + "/t" + str(mainTuple[0]))
                        except(NoSuchNodeError):
                            try:
                                group2 = openFi.getNode("/" + mainTuple[1] + "/s" + str(mainTuple[2]))
                            except(NoSuchNodeError):
                                try:
                                    group1 = openFi.getNode("/" + mainTuple[1])
                                except(NoSuchNodeError):
                                    group1 = openFi.createGroup("/", mainTuple[1], mainTuple[1])
                                group2 = openFi.createGroup(group1, "s" + str(mainTuple[2]), str(mainTuple[2]))
                            tableD = openFi.createTable(group2, "t" + str(mainTuple[0]), Tick, "Instrument")
                        tableD.append(dataArray)
                        tableD.flush()
            lock.release()
                    
        
def addDictToQueue(dictInst):
    dicts.put(dictInst)
    print dicts.qsize(),"BOOK"
    return

def changeFile():
    global currentDate
    global notset
    global openFi
    while True:
        if notset:
            lock.acquire()
            currentDate = datetime.datetime.utcnow()
            openFi = openFile("Book" + str(currentDate.year) + str(currentDate.month) + str(currentDate.day), mode="w", title=str(currentDate.day))
            notset = False
            lock.release()
        elif currentDate.day != datetime.datetime.utcnow().day:
            lock.acquire()
            if openFiBuffer != None:
                openFiBuffer.close()
            openFiBuffer = openFile("Book" + str(currentDate.year) + str(currentDate.month) + str(currentDate.day), mode="w", title=str(currentDate.day))
            multiInstances = True
            lock.release()
            time.sleep(1200)
            lock.acquire()
            currentDate = datetime.datetime.utcnow()
            openFi.close()
            openFi = openFiBuffer
            multiInstances = False
            lock.release()

dictsTrade = Queue.Queue()
openFiTrade = None
openFiBufferTrade = None
currentDateTrade = None
notsetTrade = True
multiInstancestrade = False

class TickTrade(IsDescription):
    primaryTime = UInt32Col()
    secondaryTime = UInt32Col()
    price = UInt64Col()
    quant = UInt64Col()
    
#def updateBook(instrument, timestamp, side, level, price, quant, orders, monthyear, day):
#    global group
#    if day != currentDayOfMonth:
#        currentDayOfMonth = day
#        group = file.createGroup("/", "day" + str(day), 'Day of Month')
#    try:
#        table = file.getNode("/day" + str(day), "tick" + str(instrument))
#    except (NoSuchNodeError):
#        table = file.createTable(group, "tick" + str(instrument), Tick, str(instrument) + "Tick")
#        #table.cols.timestamp.createIndex()
#    table.row['timestamp'] = timestamp
#    table.row['side'] = side
#    table.row['level'] = level
#    table.row['price'] = price
#    table.row['quant'] = quant
#    table.row['orders'] = orders
#    table.row.append()
#    table.flush()
#    file.flush()
#    return

def acceptDictTrade():
    while True:
        while not dictsTrade.empty():
            lock.acquire()
            dictInst = dictsTrade.get()
            for mainTuple, dataArray in dictInst.iteritems():
                if not(multiInstancestrade):
                    try:
                        tableD = openFiTrade.getNode("/" + mainTuple[1] + "/t" + str(mainTuple[0]))
                    except(NoSuchNodeError):
                        try:
                            group1 = openFiTrade.getNode("/" + mainTuple[1])
                        except(NoSuchNodeError):
                            group1 = openFiTrade.createGroup("/", mainTuple[1], mainTuple[1])
                        tableD = openFiTrade.createTable(group1, "t" + str(mainTuple[0]), TickTrade, "Instrument")
                    tableD.append(dataArray)
                    tableD.flush()
                else:
                    if mainTuple[3] != TimeHandler.getYearMonthDay(currentDateTrade):
                        try:
                            tableD = openFiBufferTrade.getNode("/" + mainTuple[1] + "/t" + str(mainTuple[0]))
                        except(NoSuchNodeError):
                            try:
                                group1 = openFiBufferTrade.getNode("/" + mainTuple[1])
                            except(NoSuchNodeError):
                                group1 = openFiBufferTrade.createGroup("/", mainTuple[1], mainTuple[1])
                            tableD = openFiBufferTrade.createTable(group1, "t" + str(mainTuple[0]), TickTrade, "Instrument")
                        tableD.append(dataArray)
                        tableD.flush()
                    else:
                        try:
                            tableD = openFiTrade.getNode("/" + mainTuple[1] + "/t" + str(mainTuple[0]))
                        except(NoSuchNodeError):
                            try:
                                group1 = openFiTrade.getNode("/" + mainTuple[1])
                            except(NoSuchNodeError):
                                group1 = openFiTrade.createGroup("/", mainTuple[1], mainTuple[1])
                            tableD = openFiTrade.createTable(group1, "t" + str(mainTuple[0]), TickTrade, "Instrument")
                        tableD.append(dataArray)
                        tableD.flush()
            lock.release()
                    
        
def addDictToQueueTrade(dictInst):
    dictsTrade.put(dictInst)
    print dictsTrade.qsize(), "TRADE"
    return

def changeFileTrade():
    global currentDateTrade
    global notsetTrade
    global openFiTrade
    while True:
        if notsetTrade:
            lock.acquire()
            currentDateTrade = datetime.datetime.utcnow()
            openFiTrade = openFile("Trade" + str(currentDateTrade.year) + str(currentDateTrade.month) + str(currentDateTrade.day), mode="w", title=str(currentDateTrade.day))
            notsetTrade = False
            lock.release()
        elif currentDateTrade.day != datetime.datetime.utcnow().day:
            lock.acquire()
            if openFiBufferTrade != None:
                openFiBufferTrade.close()
            openFiBufferTrade = openFile("Trade" + str(currentDateTrade.year) + str(currentDateTrade.month) + str(currentDateTrade.day), mode="w", title=str(currentDateTrade.day))
            multiInstancestrade = True
            lock.release()
            time.sleep(1200)
            lock.acquire()
            currentDateTrade = datetime.datetime.utcnow()
            openFiTrade.close()
            openFiTrade = openFiBufferTrade
            multiInstancestrade = False
            lock.release()