from pyspark import SparkConf, SparkContext
import os
u_item = os.path.abspath("C:\\Users\\mojiway\\Desktop\\tutorials\\Udemy - Taming Big Data with Apache Spark and Python - Hands On!0\\myDataFiles\\ml-100k\\u.ITEM")
u_data = os.path.abspath("C:\\Users\\mojiway\\Desktop\\tutorials\\Udemy - Taming Big Data with Apache Spark and Python - Hands On!0\\myDataFiles\\ml-100k\\u.data")
def loadMovieNames():
    movieNames = {}
    with open(u_item) as f:
        for line in f:
            fields = line.split('|')
            movieNames[int(fields[0])] = fields[1]
    return movieNames

conf = SparkConf().setMaster("local").setAppName("PopularMovies")
sc = SparkContext(conf = conf).getOrCreate()

nameDict = sc.broadcast(loadMovieNames())

lines = sc.textFile(u_data)
movies = lines.map(lambda x: (int(x.split()[1]), 1))
movieCounts = movies.reduceByKey(lambda x, y: x + y)

flipped = movieCounts.map( lambda x : (x[1], x[0]))
sortedMovies = flipped.sortByKey()

sortedMoviesWithNames = sortedMovies.map(lambda countMovie : (nameDict.value[countMovie[1]], countMovie[0]))

results = sortedMoviesWithNames.collect()

for result in results:
    print (result)
