import csv
import sys
from plexapi.server import PlexServer

try:
    import apiconfig
except:
    print("Error!")
    print("  \"apiconfig.py\" seems to be missing!")
    print("  Have you copied the default config to \"apiconfig.py\" and made appropriate edits?")
    print()
    sys.exit()

raw_file = open("movielist.csv", "w", newline='')
csv_file = csv.writer(raw_file)
csv_file.writerow(["Movie Name","Year", "View Count", "English Subtitles"])

plex = PlexServer(apiconfig.baseurl, apiconfig.token)
movies = plex.library.section(apiconfig.libraryname).all()
count = 0
print("Searching for english subtitles...", end='', flush=True)
for video in movies:
    has_eng_sub = False
    if len(video.subtitleStreams()) > 0:
        for sub in video.subtitleStreams():
            if isinstance(sub.languageCode, str) and sub.languageCode.lower() == "eng":
                has_eng_sub = True
    
    #if has_eng_sub:
    #    print(f"{video.title} ({video.year}) has english subtitle")
    csv_file.writerow([video.title, video.year, video.viewCount, ("Yes" if has_eng_sub else "No")])
    count += 1
    if count % 10 == 0:
        print(".", end='', flush=True)
    if count % 100 == 0:
        print(count, end='', flush=True)
    #if count > 200:
    #    print()
    #    sys.exit()

raw_file.close()