import SetsCreator
import RecommendationTreeCreator
import time
import concurrent
from matplotlib.pyplot import *
from graph_tool.all import *
from MovieRecommender import generateRecommendations, computeMeanAveragePrecision



k = 1
print("Count of iterations before averaging results: " + str(k))
for numberOfAnalysedMovies in range(10, 11, 10):
    for numberOfRecommendedMovies in range(3,4,2):
        for treshold in range (199, 200, 50):
            averageTime = 0
            TOPmMAP = 0
            ALGmMAP = 0
            time1 = time.time()
            for i in range(0,k):
                movies = SetsCreator.readMovies()
                users = SetsCreator.createUserSet(SetsCreator.readRatings(numberOfAnalysedMovies), movies)
                trainingSet = users[0]
                testSet = users[1]
                tree = RecommendationTreeCreator.create_decision_tree(trainingSet, movies, 72000)
                TOPmMAP = TOPmMAP + computeMeanAveragePrecision(trainingSet, testSet, tree, numberOfRecommendedMovies)
                starTime = time.time()
                tree = RecommendationTreeCreator.create_decision_tree(trainingSet, movies, treshold)
                endTime = time.time()
                averageTime += (endTime - starTime)
                ALGmMAP = ALGmMAP + computeMeanAveragePrecision(trainingSet, testSet, tree, numberOfRecommendedMovies)
            time2 = time.time()
            TOPmMAP /= k
            ALGmMAP /= k
            averageTime /= k
            #trees[0].view()
            print("Count of:")
            print("Analysed movies:     " + str(numberOfAnalysedMovies))
            print("Recommended movies:  " + str(numberOfRecommendedMovies))
            print("Users at leaf:       " + str(treshold))
            print("Best-rated mMAP:     " + str(TOPmMAP))
            print("Algorithm mMAP:      " + str(ALGmMAP))
            print("Average clock time of recommendation tree construction: " +str(averageTime) + " seconds")
            print("         "+ str(time2-time1))
            print("         ")
            
#Destroy and draw the final tree
for v in tree.vertices():
    attribute = tree.vp.attribute[v]
    if attribute == "leaf" :
        recommendations = tree.vp.recommendations[v]
        stringRecommendations = "Recommendations: "
        for r in recommendations:
            stringRecommendations += next(iter([m for m in movies if m.movieId == r])).title
            stringRecommendations += ", "
        tree.vp.attribute[v] = stringRecommendations
    if isinstance(attribute, int):
        tree.vp.attribute[v] = next(iter([m for m in movies if m.movieId == attribute])).title
graph_draw(
    tree,
    vertex_text=tree.vertex_properties["attribute"],
    vertex_text_position="centered",
    edge_text = tree.edge_properties["affinity"],
    vertex_size=10,
    edge_pen_width=1.2,
    vcmap=matplotlib.cm.gist_heat_r)
