from flask import Flask,Response,request
from flask_restful import Api, Resource, reqparse
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import argparse
import requests
import json
import re
import configparser

app_id='8a23255ffd764060a792849f5ef701b2'
app_secret='f459a687004546fabe34e7955f3800f4'
app_url='https://www.socialmediawall.io/api/v1.1/'
analyser = SentimentIntensityAnalyzer()


 # From scores, extract the value that matches key. Key can be pos,neg,neu or compound
def get_indicator(scores,key):
    res=str(scores).find(key)
    s=str(scores)
    start=res+5
    end=start+6
    st=s[start:end]
    return st

 # 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


 # Test API call to know the score of a sentence
def sentiment_analyzer_scores_test(sentence):
     score = analyser.polarity_scores(sentence)
     return("{:-<40} {}".format(sentence, str(score)))

 # Call to Vader Sentiment Analyser to get the polarity scores and return pos if positive neg if negative
def sentiment_analyzer_scores(sentence):
     score = analyser.polarity_scores(sentence)
     pos=get_indicator(score,'pos')
     neg=get_indicator(score,'neg')
     neu=get_indicator(score,'neu')
     com=get_indicator(score,'com')
     if(pos>neg):
     # and pos>neu):
         return "com"
     else:
        # if(neg>neu):
         return "neg"
         #else:
          #   print("\nIts Neutral")
     print("{:-<40} {}".format(sentence, str(score)))

def getData(wall_id):
     return call_api(wall_id)
