from datetime import datetime
from time import sleep

from apscheduler.schedulers.blocking import BlockingScheduler

from data.data_provider import *
from db.sql_aclhemy_models import *
from scripts.train import *

sched = BlockingScheduler()


def classify_collected_tweets(symbol):
    print('Classifying collected Tweets...')
    # load classifier saved with pickle
    saved_classifier = open('vote_classifier.pickle', 'rb')
    vote_classifier = pickle.load(saved_classifier)
    saved_classifier.close()

    # TODO fix saving the date for filtered tweets

    # get collected unclassified tweets from database
    unclassified_tweets = []
    unclassified_tweets_texts = []

    db_session = get_session()
    for tw in db_session.query(Tweet).all():
        unclassified_tweets.append(tw)
        unclassified_tweets_texts.append(tw.text)
    db_session.close()

    # filter data

    filtered_tweets = filter_data(unclassified_tweets_texts[-25:])

    # classify all tweets and save them to database
    db_session = get_session()

    for tweet in filtered_tweets:
        tweet_features = build_feature_set1(tweet)
        vote = vote_classifier.classify(tweet_features)
        conf = vote_classifier.confidence()
        tw = FilteredTweet()
        tw.text = ' '.join(tweet)
        tw.classification = vote
        tw.symbol = symbol
        tw.confidence = conf
        # print(tw.classification.upper(), conf, tw.text)
        db_session.add(tw)

    db_session.commit()
    db_session.close()


def job():
    print('Started job at:', str(datetime.now()))
    collect_tweets('tsla')
    sleep(1)
    classify_collected_tweets('TSLA')
    print('Finished job at:', str(datetime.now()))

# use hours corresponding to the local timezone in respect to New York time
# these are the after-market and pre-market hours when Twitter users are most active
sched.add_job(job, 'cron', day_of_week='mon-fri', hour='21,22,23,0,1,2,3,14,15', minute=16)
sched.start()


