#!/bin/env python
#Display the top 10 account who have posted a certain term.
#2022 Sallust
#API docs: https://api.smat-app.com/docs

import requests
import argparse
#import plotly.express as px

parser = argparse.ArgumentParser(description='Top Users on Site Based on Term',epilog='eg: smat-query --chart -t nigger -s kiwifarms -S 2022-01-01 -U 2022-05-30')
parser.add_argument('--term', '-t', type=str, required=True, help='Search term. ex: nigger')
parser.add_argument('--site', '-s', type=str, required=True, help='Site to search ex: kiwifarms')
parser.add_argument('--since', '-S', type=str, required=True, help='Date to begin search. Format YYYY-MM-DD')
parser.add_argument('--until', '-U', type=str, required=True, help='Date to end search.')
parser.add_argument('--chart', '-C', action='store_true', help='Create a bar chart(requires plotly-chart-generator)')
parser.add_argument('--esquery', '-E', action='store_true', help='Use esquery. Will search beyond the message body, catching the username and other metadata.')
parser.add_argument('--debug', '-D', action='store_true', default=False, help='')


args = parser.parse_args()
sort = "false"

#Granular times can be used but usually not necessary
#ex:
#https://api.smat-app.com/activity?term=nigger&site=kiwifarms&since=2022-03-31&until=2022-05-31&esquery=true

api_url = "https://api.smat-app.com/activity?term={0}&site={1}&since={2}&until={3}&esquery={4}&sortdesc={5}".format(args.term,args.site,args.since,args.until,args.esquery,sort)
response = requests.get(api_url)
response_json = (response.json())
if args.debug:
    print(response_json)
stats = response_json["aggregations"]["author_username"]["buckets"]


#Print user stats
for i in stats:
    print(i["key"] + ":" + str(i["doc_count"]))

#Create chart via plotly
if args.chart:
    import plotly.express as px
    x = []
    y = []
    #Plotly wants two lists for x and y. Convert dict entries into lists
    for i in stats:
        x.append(i["key"])
        y.append(i["doc_count"])
    #print(x,y)


    #create bar plot
    title = "Occurances of {0} by user from {1} to {2}".format(args.term,args.since,args.until)
    fig = px.bar(
            x=x, y=y,
            title=title
    )
    if args.debug:
        print(fig)
    fig.show()







