from optparse import OptionParser
from utils import *
import models
from sqlalchemy.orm import sessionmaker, mapper
import logging
import time
import twitter
import sys

APPLICATION_NAME = "Tweet recorder user"
CONSUMER_KEY = "Vdr5ZcsjI1G3esTPI8yDg"
CONSUMER_SECRET = "LMhNrY99R6a7E0YbZZkRFpUZpX5EfB1qATbDk1sIVLs"


def get_options():
    parser = OptionParser()
    parser.add_option("-d", "--database", dest="database",
                      help="Input database", metavar="DATABASE")
    parser.add_option("-s", "--start-date", dest="start_date",
                      help="start date", metavar="START_DATE")
    parser.add_option("-e", "--end-date", dest="end_date",
                      help="end date", metavar="END_DATE")
    parser.add_option("-H", "--hashtag", dest="hashtag",
                      help="Hashtag", metavar="HASHTAG", default=[], action="append")                      
    parser.add_option("-x", "--exclude", dest="exclude",
                      help="file containing the id to exclude", metavar="EXCLUDE")
    parser.add_option("-D", "--duration", dest="duration", type="int",
                      help="Duration", metavar="DURATION", default=None)
    parser.add_option("-m", "--message", dest="message",
                      help="tweet", metavar="MESSAGE", default="")    
    parser.add_option("-u", "--user", dest="user",
                      help="user", metavar="USER")    
    parser.add_option("-w", "--password", dest="password",
                      help="password", metavar="PASSWORD")    
    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_options()
    
    set_logging(options)
        
    logging.debug("OPTIONS : " + repr(options))

    if not options.message or len(options.message) == 0:
        sys.exit()

    engine, metadata = setup_database('sqlite:///'+options.database, echo=((options.verbose-options.quiet)>0), create_all = False)        
    
    Session = sessionmaker()
    conn = engine.connect()
    try :
        session = Session(bind=conn)
        try:
            metadata = MetaData(bind=conn)
            tweet_exclude_table = Table("tweet_exclude", metadata, Column('id', BigInteger, primary_key=True), prefixes=['TEMPORARY'])
            #mapper(TweetExclude, tweet_exclude_table)
            metadata.create_all()

            start_date_str = options.start_date
            end_date_str = options.end_date
            duration = options.duration
            hashtags = options.hashtag
            
            
            start_date = parse_date(start_date_str) 
            ts = time.mktime(start_date.timetuple())
        
            if end_date_str:
                end_date = parse_date(end_date_str)
                te = time.mktime(end_date.timetuple())
            else:
                te = ts + duration
                end_date = start_date + datetime.timedelta(seconds=duration)
            
            query = get_user_query(session, start_date, end_date, hashtags, tweet_exclude_table)
            #query = query.filter(User.screen_name == "tibo_c")
                
            query_res = query.all()
            
            acess_token_key, access_token_secret = get_oauth_token(options.token_filename, application_name=APPLICATION_NAME, consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET)
            t = twitter.Twitter(auth=twitter.OAuth(acess_token_key, access_token_secret, CONSUMER_KEY, CONSUMER_SECRET))

            for user in query_res:
                screen_name = user.screen_name
                
                message = u"@%s: %s" % (screen_name, options.message.decode(sys.getfilesystemencoding()))
                logging.debug("new status : " + message)
                t.statuses.update(status=message)
                

        finally:
            session.close()
    finally:
        conn.close()

