import requests
import re
import os
import sqlite3
import matplotlib.pyplot as plt

def spotify_pop(cur, conn):
    """
    Input: Database cursor and connection.
    Output: Returns a list of tuples in the format (song, spotify popularity score) in descending order of score.
    Purpose: to rank top 100 hummed songs by spotify popularity. 
    """
    cur.execute('SELECT Spotify_Popularity_Scores.track, Spotify_Popularity_Scores.popularity FROM Spotify_Popularity_Scores')
    tupleslst = cur.fetchall()
    conn.commit()
    lst2 = sorted(tupleslst, key=lambda x: x[1], reverse=True)
    return lst2

def billboard_pop(cur, conn):
    """
    Input: Database cursor and connection.
    Output: Returns a list of tuples in the format (song, humming popularity) in descending order of humming popularity.
    Purpose: to rank top 100 hummed songs in tuples. 
    """
    cur.execute('SELECT Billboard.song, Billboard.song_id FROM Billboard')
    tupleslst = cur.fetchall()
    conn.commit()
    return tupleslst

def compare_top_20(lst1, lst2):
    """
    Input: the two tuple lists generated by the above functions.
    Output: Returns a dictionary with song titles as keys and a [billboard ranking, spotify popularity score]
    formatted list
    Purpose: to make data visualization easier
    """
    dic = {}
    for x in lst1:
        for y in lst2:
            if x[0][:5] == y[0][:5]:
                lst = []
                lst.append(y[1])
                lst.append(x[1])
                dic[x[0]] = lst
    return dic

def avg_score_comparison_2(dic):
    """
    Input: dictionary of song keys and score values.
    Output: visualization assessing correlation between Spotify popularity scores and
    our calculated average popularity score (average of Spotify score and humming score)
    Purpose: to assess whether our average popularity score is more greatly correlated with 
    Spotify popularity scores or Humming popularity scores, which can be done by 
    comparing this with visualization 2.
    """
    bill = []
    spot = []
    for x in dic:
        bill.append(dic[x][0])
        spot.append(dic[x][1])
    spot2 = sorted(spot, reverse=True)
    avg_lst = []
    tupls = zip(bill, spot2)
    scores = list(tupls)
    for x in scores:
        avg = (x[0] + x[1])/2
        avg_lst.append(avg)
    plt.plot(spot, avg_lst, 'go')
    plt.axis([0,100,0,100])
    plt.xlabel('Spotify popularity score of songs (low to high)')
    plt.ylabel('Average score (average of humming pop score and spotify pop score) (low to high)')
    plt.title('Correlation between songs spotify popularity score and average popularity score')
    plt.show()

def main():
    """
    Acesses database data and calls functions to make visualizations.
    """
    path = os.path.dirname(os.path.abspath(__file__))
    conn = sqlite3.connect(path+'/MostHummed100.db')
    cur = conn.cursor()
    spot = spotify_pop(cur, conn)
    bill = billboard_pop(cur, conn)
    dic = compare_top_20(spot, bill)
    avg_score_comparison_2(dic)
    conn.close()


if __name__ == "__main__":
    main()