from iri_tweet.models import setup_database
from iri_tweet.processor import TwitterProcessorStatus
from iri_tweet.utils import set_logging_options, set_logging
from optparse import OptionParser
import logging
import sqlite3

logger = logging.getLogger(__name__)


#    'entities': "tweet_entity",     
#    'user': "tweet_user"

def get_option():
    
    parser = OptionParser()

    parser.add_option("-t", dest="token_filename", metavar="TOKEN_FILENAME", default=".oauth_token",
                      help="Token file name")

    set_logging_options(parser)

    return parser.parse_args()

if __name__ == "__main__":
    
    (options, args) = get_option()
        
    set_logging(options)
    
    with sqlite3.connect(args[0]) as conn_in:
        engine, metadata, Session = setup_database('sqlite:///'+args[1], echo=((options.verbose-options.quiet)>0))
        session = Session()
        try:
            curs_in = conn_in.cursor()
            fields_mapping = {}
            for i,res in enumerate(curs_in.execute("select json from tweet_tweet;")):
                logger.debug("main loop %d : %s" % (i, res[0])) #@UndefinedVariable
                processor = TwitterProcessorStatus(json_dict=eval(res[0]), json_txt=res[0], source_id=None, session=session, consumer_token=None, access_token=None, token_filename=options.token_filename, user_query_twitter=False, logger=logger)
                processor.process()
                session.commit()
            logger.debug("main : %d tweet processed" % (i+1)) #@UndefinedVariable
        except Exception, e:
            session.rollback()
            raise e
        finally:
            session.close()
            
    
    