from os import path
import shutil
from random import randint

#
# This script was written by pet@fet.at in 1.2021
# It is used by the FET_infoscreen bot
# It gets an image, saves it in a folder and moves the oldest image into a different one
# 10 Images is preconfigured
#


def photoDownload(photo, username, userid):

    #save file after checking if we've got a collision
    filepath = "../slideshow/"+username+"-"+userid+"-"+str(randint(10, 1000))+".jpg" #first try with lower numbers
    while path.exists("filepath"):
        filepath = "../slideshow/"+username+"-"+userid+"-"+str(randint(1000, 99999999))+".jpg"
    photo.download(filepath)

    recent_images_file = open("recent_images.txt", "r")
    recent_images = recent_images_file.readlines()
    recent_images.append(filepath) # add the newest photo
    recent_images_file.close()
    print(recent_images)

    if len(recent_images) >= 10:
        first_image = 0
    else:
        first_image = 1

    recent_images_file = open("recent_images.txt", "w")

    for image in recent_images:
        #print("Image: "+str(image.strip()))
        if first_image == 0:
            #print(str(image.strip() + " moved to old.")
            image_name= image.split("slideshow/",1)[1] # get the image name without path
            try: #try to move it if it has not been deleted
                shutil.move(image.rstrip(), "../slideshow/old/"+image_name)
            except:
                pass
            first_image = 1
        else:
            #print(image.strip() + " saved.")
            recent_images_file.write(image.rstrip() + "\n")


    recent_images_file.close()
