# google_play_store.py

# This analyzes googleplaystore.csv from here:
#    https://www.kaggle.com/lava18/google-play-store-apps

# That file had commas in some fields, so we opened it (in Excel),
# and removed all commas (replace-all with empty string),
# and saved that as googleplaystore-no-commas.csv, which we use here.

# This is written without lists, since we have not covered them yet.
# Some of this would be easier or more efficient with lists...
# Still, it's cool how much we can already do without them!  Woohoo!

def readFile(path):
    # copied from the 110 course notes
    with open(path, 'rt', encoding="ascii", errors="surrogateescape") as f:
        return f.read()

def getCategories():
    contents = readFile('googleplaystore-no-commas.csv')
    categories = ''
    for line in contents.splitlines():
        app,category,rating,reviews,size,installs,appType,price,contentRating,genres,lastUpdated,currentVer, androidVer = line.split(',')
        category = category.lower().replace('_',' ')
        if (category not in categories):
            categories += category + '\n'
    return categories

def listCommands():
    print('''Commands:
    l    list commands
    q    quit
    c    print categories
    b    print best in category
    w    print worst in category
''')

def getCommand():
    while True:
        command = input('Command --> ').lower()
        if (command in 'lqcbw'):
            return command
        print('Illegal command.')
        listCommands()

def getCleanRating(rating):
    # should be a number between 0 and 5
    # if not clean, we'll just use 2.5 here (could be more graceful...)
    if (rating == 'NaN'): rating = 2.5
    return float(rating)

def getCleanReviews(reviews):
    # should be a non-negative integer
    if (reviews.endswith('M')):
        # need to convert '3.0M' to 3000000
        return int(float(reviews[:-1])*1000000)
    else:
        return int(reviews)

def printBestInCategory():
    targetCategory = input('For which category (partial names ok) --> ')
    contents = readFile('googleplaystore-no-commas.csv')
    bestRating = bestReviews = 0
    bestApp = None
    for line in contents.splitlines()[1:]: # note: [1:] skips header line
        app,category,rating,reviews,size,installs,appType,price,contentRating,genres,lastUpdated,currentVer, androidVer = line.split(',')
        category = category.lower().replace('_',' ')
        rating = getCleanRating(rating)
        reviews = getCleanReviews(reviews)
        if (targetCategory in category):
            if ((rating > bestRating) or
                ((rating == bestRating) and (reviews > bestReviews))):
                bestRating = rating
                bestReviews = reviews
                bestApp = app
    print('Best app in category:', targetCategory)
    print('   app:', bestApp)
    print('   rating:', bestRating)
    print('   reviews:', bestReviews)

def printWorstInCategory():
    targetCategory = input('For which category (partial names ok) --> ')
    contents = readFile('googleplaystore-no-commas.csv')
    worstRating = 100
    worstReviews = 0
    worstApp = None
    for line in contents.splitlines()[1:]: # note: [1:] skips header line
        app,category,rating,reviews,size,installs,appType,price,contentRating,genres,lastUpdated,currentVer, androidVer = line.split(',')
        category = category.lower().replace('_',' ')
        rating = getCleanRating(rating)
        reviews = getCleanReviews(reviews)
        if (targetCategory in category):
            if ((rating < worstRating) or
                ((rating == worstRating) and (reviews > worstReviews))):
                worstRating = rating
                worstReviews = reviews
                worstApp = app
    print('Worst app in category:', targetCategory)
    print('   app:', worstApp)
    print('   rating:', worstRating)
    print('   reviews:', worstReviews)

def googlePlayStoreDataExplorer():
    print('Google Play Store Data Explorer!\n')
    listCommands()
    while True:
        command = getCommand()
        if (command == 'q'):
            print('Goodbye!')
            return
        elif (command == 'c'):
            print(getCategories())
        elif (command == 'b'):
            printBestInCategory()
        elif (command == 'w'):
            printWorstInCategory()
        else:
            print('Unknown command:', command)
            listCommands()

googlePlayStoreDataExplorer()
