#!/usr/bin/python
from twisted.internet import task, protocol, reactor
from aae import AaeConsoleFactory, FilterList 
from aae import Config
from pyaae import Hashtree, Msgpuller
import argparse
from os.path import isdir
from shutil import rmtree

CONF_FILE = 'nodemon.xml'
DB_NAME = '.db'

def update_filter_list():
   fl.update()

if __name__ == '__main__':
   parser = argparse.ArgumentParser()
   parser.add_argument('-c', '--config', default=CONF_FILE, help='the config file.(default:nodemon.xml)')
   args = parser.parse_args()
   config = Config(args.config)
#   if isdir(DB_NAME):
#      rmtree(DB_NAME)
   ht = Hashtree(DB_NAME) 
   info = config.get_metadb_info()
   fl = FilterList(info)
   #update filter list periodically.
   l = task.LoopingCall(update_filter_list)
   l.start(10)
   #start msg puller
   mp = Msgpuller(args.config, ht, fl._filterlist)
   mp.start()
   #start console
   ip, port = config.get_console_info()
   reactor.listenTCP(port, AaeConsoleFactory(ht, fl, config), interface=ip) 
   reactor.run()
   
