import os
import subprocess
import commands
import socket
import random
import threading
from PIL import Image
import time
import sys
import fnmatch

frameBufferCommand = "sudo fbi -T 1 -d /dev/fb0 -noverbose "
omxplayerCommand = "omxplayer -b "
moviePosterLocation = "/home/pi/movieposters/"
turnOffScreen = "sudo /opt/vc/bin/tvservice -o"
turnOnScreen = "sudo /opt/vc/bin/tvservice -p"
screenState = False
oldProcessID = 0
oldProcessKilled = False

#FUNCTIONS

def searchDirectory(Location):
    directorySearched = False
    fileCount = next(os.walk(Location))[2] #get the number of available posters
    print('Current # Of Posters in Directory: ' + str(len(fileCount)))
    maxNumber = len(fileCount) - 1
    posterToDisplay = random.randint(0, maxNumber)
    return fileCount[posterToDisplay]    

def displayVideo(videoToDisplay):
    try:
        print("About to Play Poster Video")
        os.system(omxplayerCommand + videoPosterLocation + videoToDisplay)
        videoFunctionSuccess = True
    except IndexError as msg:
        print(msg)
        videoFunctionSuccess = False
        return videoFunctionSuccess
    return videoFunctionSuccess

def displayPoster(posterToDisplay):
    posterFunctionSuccess = False
    while not posterFunctionSuccess:
        try:
            image = Image.open(moviePosterLocation + posterToDisplay) #open the current image
            width, height = image.size
        except IndexError as msg:
            print("encountered an IndexError while opening the image")
            width = 0
            height = 0 
            posterFunctionSuccess = False
            return posterFunctionSuccess     
        except IOError as msg:
            print(msg)
            posterFunctionSuccess = False
            return posterFunctionSuccess   
        if width > height:
            if attemptNumber > 5:
                print("Too Many Attempts, Stopping")
                posterFunctionSuccess = False
                return posterFunctionSuccess
                break
            else:
                print("We Think This Isnt A Poster, Trying Again")               
                continue
        else:
            try:
                print("About to Open Image")
                os.system(frameBufferCommand + moviePosterLocation + posterToDisplay)
                posterFunctionSucces = True
            except IndexError as msg:
                print(msg)
                posterFunctionSuccess = False
                return posterFunctionSuccess
            return posterFunctionSuccess             

def killFrameBuffer():
    try:
        os.system("sudo killall fbi")
    except OSError as msg:
        print("OS Error Killing Frame Buffer")
    try:
        os.system("sudo killall omxplayer")
    except OSError as msg:
        print("Error Killing omxplayer")

#MAIN THREAD
def client():
    global oldProcessID
    global screenState
    global oldProcessKilled
    oldProcessKilled = False

    while True:
        # -------- DISPLAY RANDOM MOVIE POSTER

        randomMoviePoster = searchDirectory(moviePosterLocation)
        displayPoster(randomMoviePoster)

        # -------- Kill Old Process
        try:
            processObject = subprocess.Popen(['ps', '-aux'], stdout=subprocess.PIPE)
            out, err = processObject.communicate()
            for line in out.splitlines():
                if 'fbi' in line:
                    comparisonLabel = line.split(None)[16]
                    processToKill = int(line.split(None)[1])
                    if randomMoviePoster in comparisonLabel:
                        print(randomMoviePoster + " is equal to " + comparisonLabel + ", so we dont want to kill it, because that is the current poster")
                    else:
                        print(randomMoviePoster + " is NOT equal to " + comparisonLabel + ", so we want to kill any running FBI processes that are not our current poster")
                        os.kill(processToKill, 9)
                else:
                    print("We didnt find 'fbi' in this line so we dont fucking care.") 
        except OSError as msg:
            print(msg)
            break

        # ------------ WAIT FOR 10 MINUTES

        time.sleep(600)
try:
    try:
        os.system("sudo killall fbi")
    except OSError as msg:
        print(msg)

    serverThread = threading.Thread(target = client)
    serverThread.start()
except KeyboardInterrupt: 
    print("Keyboard Interrupt Activated Closing Program")
    sys.exit()
