import requests, imdb, discord, json
from funcs import logThis

url = "http://localhost:7878/api/v3/"
moviePath = "/media/plex/Server/movies/"

class BedreNetflix():
    def __init__(self,bot):
        self.bot = bot

    #Returns a list of no more than 5 options when user requests a movie
    async def requestMovie(self, ctx, movieName):
        logThis("Searching for "+movieName)
        movies = imdb.IMDb().search_movie(movieName)
        if len(movies) > 5:
            movies = movies[:5]

        if len(movies) == 1:
            messageTitle = "**Is it this movie?**"
        else:
            messageTitle = "**Is it any of these movies?**"

        messageText = ""
        imdbIds = []

        for x, movie in enumerate(movies):
            messageText += "\n"+str(x+1)+") "+movie["title"]+" ("+str(movie["year"])+")"
            imdbIds.append(movie.movieID)

        logThis("Returning a list of "+str(len(movies))+" possible movies: "+str(imdbIds))

        em = discord.Embed(title=messageTitle,description=messageText,colour=0x00FF00)

        message = await ctx.send(embed=em)

        messageData = {"messageID":message.id,"imdbIds":imdbIds}

        with open("resources/bedreNetflix/oldMessage"+str(ctx.channel.id),"w") as f:
            json.dump(messageData,f)

        if len(movies) == 1:
            await message.add_reaction("✔️")
        else:
            for x in range(len(movies)):
                await message.add_reaction(["1️⃣","2️⃣","3️⃣","4️⃣","5️⃣"][x])

        await message.add_reaction("❌")

    #Adds the requested movie to Bedre Netflix
    async def addMovie(self,channel,imdbId):
        if imdbId == None:
            logThis("Did not find what the user was searching for")
            await channel.send("Try searching for the IMDB id")
        else:
            logThis("Trying to add movie "+str(imdbId))
            apiKey = self.bot.credentials.radarrKey
            response = requests.get(url+"movie/lookup/imdb?imdbId=tt"+imdbId+"&apiKey="+apiKey)
            lookupData = response.json()
            postData = {"qualityProfileId": 1,
            "rootFolderPath" : moviePath,
            "monitored" : True,
            "addOptions": {"searchForMovie": True}}
            for key in ["tmdbId","title","titleSlug","images","year"]:
                postData.update({key : lookupData[key]})

            r = requests.post(url= url+"movie?apikey="+apiKey,json = postData)

            if r.status_code == 201:
                await channel.send("Movie successfully added to Bedre Netflix")
                logThis("Added a movie to Bedre Netflix")
            elif r.status_code == 400:
                await channel.send("The movie is already on Bedre Netflix")
            else:
                await channel.send("Something went wrong")
                logThis(str(r.status_code)+" "+r.reason)
