from flask import Flask,Response,jsonify, abort, request, json
from flask_restful import Api, Resource, reqparse
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from sqlalchemy.orm.exc import NoResultFound
from conf.configurations import Configurations
from db.models import SentimentAnalysisDataModel
from conf.database import Database
import argparse
import requests 
import json
import re
import wsgiref
import schedule
import datetime
import time


configurations = Configurations()
analyser = SentimentIntensityAnalyzer()
db       = Database()

configParser = configurations.getConfigParser()
app_id = configParser.get('SOICALWALLDEV', 'appid')
app_secret = configParser.get('SOICALWALLDEV', 'appsecret')
app_url    = configParser.get('SOICALWALLDEV', 'url')
         
   

# Calls Social IO API with given wallid and returns total positive or negative posts    
def call_api(wallid):
     url=app_url+str(wallid)+'/posts/?app_id='+app_id+'&app_secret='+app_secret
     resp = requests.get(url)
     jsonobj=resp.json()
     c=0
     score =0
     com = 0

     for data in jsonobj['data']['posts']:
             line = re.sub('[@#$]', '', data['text'])
             print(str(data['postid'] )+ "----------------------"+line.rstrip())
             result=analyser.polarity_scores(line.rstrip("\n"))
             print("{:-<40} {}".format(line.rstrip("\n"), str(result)))
             score = score + result['compound']
             c     = c+1
             com   = score / c
             #print(score)


     analyze=json.dumps({"count":str(c),"compound":str(com)})
     return analyze 

def get_sentiment_reward_config(cumulative_compound_score):
    try:
        line = "SELECT MAX(SentimentRewardConfigID.id) AS id,\
                       SentimentRewardConfigID.reward_name,\
                       SentimentRewardConfigID.rewad_desc,\
                       SentimentRewardConfigID.emotions\
                FROM( \
                    SELECT reward_name, \
                           rewad_desc,\
                           emotions,\
                           CASE WHEN numrange(emotions_rule) @>"+str(cumulative_compound_score)+"::numeric IS TRUE THEN id ELSE 0 END AS id \
                    FROM sentiment_reward_config WHERE status = 1 ) AS SentimentRewardConfigID \
                    WHERE SentimentRewardConfigID.id > 0 \
                    GROUP BY SentimentRewardConfigID.reward_name, \
                             SentimentRewardConfigID.rewad_desc,\
                             SentimentRewardConfigID.emotions\
                    LIMIT 1"
        results = db.fetchOne(line)
        return results
    except NoResultFound:
        return jsonify({'status':400,"message": "No records found."}), 400

def get_cumulative_compound_score():
    try:
        comsql = "SELECT SUM(cumulative_compound_score) AS cumulative_compound_score FROM sentiment_analysis_data WHERE status = 0 "
        comsqlresults = db.fetchAll(comsql)
        return comsqlresults[0]['cumulative_compound_score']
    except NoResultFound:
        return jsonify({'status':400,"message": "No records found."}), 400

def insertSentimentAnlaysisData():
    sql = " SELECT * FROM socialwall_config WHERE status = 1 "
    results = db.fetchAll(sql)
    c=0
    created_date = datetime.datetime.now()
    for row in results:
        c     = c+1
        wallid     = row['wall_id']
        walldata = call_api(wallid)
        list_data = json.loads(walldata)
        cumulative_compound_score = list_data['compound']
        no_of_posts_anlaysed = list_data['count']
        sentiment_analysis_insert = "INSERT INTO sentiment_analysis_data(campaign_id, no_of_posts_anlaysed, created_timestamp,cumulative_compound_score, wall_id) VALUES ( 1,"+str(no_of_posts_anlaysed)+",'"+str(created_date)+"',"+str(cumulative_compound_score)+","+str(wallid)+" ) "
        db.executeQuery(sentiment_analysis_insert)

    
    compound_score               = get_cumulative_compound_score()
    cumulative_compound_score    = compound_score / c
    sentiment_reward_config_data = get_sentiment_reward_config(cumulative_compound_score)
    sentiment_reward_config_id   = sentiment_reward_config_data['id']
    smiley_emotion               = sentiment_reward_config_data['emotions']
    reward                       = sentiment_reward_config_data['reward_name']
    reward_desc                  = sentiment_reward_config_data['rewad_desc']
    time                         = created_date.strftime('%I:%M:%p')

    cum_result_insert = " INSERT INTO sentiment_cumulative_result(created_date, cumulative_compound_score, sentiment_reward_config_id, reward_name, rewad_desc, emotions, reward_time) VALUES ('"+str(created_date)+"',"+str(cumulative_compound_score)+","+str(sentiment_reward_config_id)+",'"+str(reward)+"','"+str(reward_desc)+"','"+str(smiley_emotion)+"','"+str(time)+"' ) "
    db.executeQuery(cum_result_insert)

    sentiment_analysis_update = "UPDATE sentiment_analysis_data SET status = 1 WHERE status = 0 "
    db.executeQuery(sentiment_analysis_update)

    return 1
        
def job():
    insertSentimentAnlaysisData()

schedule.every(10).minutes.do(job)
while True:
    schedule.run_pending()
    time.sleep(1)