class ContinuousPhotos(PhotoBoothFunction):
    'Class to continuously take photos'

    reference_photo_image = None

    def __init__(self, photobooth):
        self.menu_text     = "Take continuous photos"

        self.booth_id      = photobooth.get_booth_id()
        self.screen        = photobooth.get_pygame_screen()
        self.filehandler   = photobooth.get_file_handler()
        self.buttonhandler = photobooth.get_button_handler()

        self.local_file_dir        = self.filehandler.get_local_file_dir()
        self.local_upload_file_dir = self.filehandler.get_upload_file_dir()
        self.remote_file_dir       = self.filehandler.get_remote_file_dir()

        self.textprinter   = TextPrinter(self.screen)
        self.imageprinter  = ImagePrinter(self.screen)
        self.photohandler  = PhotoHandler(self.screen, self.filehandler)

        self.total_pics      = 17280 # 24 hours of a photo every 5 seconds
        self.capture_delay   = 5
        self.difference_threshold = 40

    def start(self, total_pics=PhotoBoothFunction.total_pics):
        # Take and display photos
        self.total_pics = total_pics

        # Display the instructions for this photobooth function
        total_pics_msg = str(self.total_pics) + " photo"
        self.instructions  = [
                              "Press Start and stand out of shot",
                              "so a reference photo of background",
                              "can be taken",
                              "Press the Start button to begin"
                             ]
        choice = self.display_instructions()
        # If the user selected Exit, bail out
        if choice == "l":
            return

        # Set total_pics so we take our one background reference photo first
        self.set_total_pics(10000)

        self.take_photos()

    def take_photos(self):
        ################################# Step 1 - Initial Preparation ########################## 
        super(ContinuousPhotos, self).take_photos()

        ################################# Step 2 - Setup camera ################################# 
        pixel_width  = self.photo_width
        pixel_height = self.photohandler.get_aspect_ratio_height(pixel_width)

        self.camera.resolution = (pixel_width, pixel_height) 

        ################################# Step 3 - Start camera preview ######################## 
        screen_colour_fill(self.screen, config.black_colour)

        self.camera.start_preview()

        ################################# Step 4 - Prepare the user ########################

        time.sleep(self.prep_delay_short)

        ################################# Step 5 - Take Photos ################################ 
        self.take_photos_and_close_camera(self.capture_delay)

    def manipulate_photo(self, filepath):
        # Use the first photo as a background reference photo
        if self.reference_photo_image is None:
            image_dir = self.filehandler.get_local_file_dir()

            # If reference_photo_image hasn't been assigned yet, then only one photo has been taken
            file_pattern = os.path.join(image_dir, self.photo_file_prefix + "*" + self.image_extension)
            self.reference_photo_image = Image.open(self.filehandler.get_sorted_file_list(file_pattern)[0])

            # Take this opportunity to upload supporting files (HTML, etc.)
            self.upload_supporting_files()
        else:
            filepath_img  = Image.open(filepath)
            # Compare the new photo to the background reference photo
            rms = self.photohandler.rms_difference(filepath_img, self.reference_photo_image)
            print "Difference to reference image: " + str(rms)

            if rms < self.difference_threshold:
                # It looks like this photo isn't very differnt to the background
                self.filehandler.delete_file(filepath)
            else:
                # It looks like this photo is very different from the background
                self.upload_photo(filepath)


    def process_photos(self):
        pass

    def upload_photos(self):
        pass

    # Create a thumbnail of the first image in the series
    def create_thumbnail(self):
        thumb_width = 200

        file_list = self.filehandler.get_sorted_file_list(os.path.join(self.local_file_dir, '*' + 
                                                       self.image_extension))
        img = self.photohandler.resize_image(file_list[0], thumb_width, thumb_width)
        img.save(os.path.join(self.local_file_dir, 'photobooth_thumb' + self.image_extension))

    def upload_supporting_files(self):
        remote_upload_dir = time.strftime("%d-%b-%Y_C")
        if self.booth_id is not "":
            remote_upload_dir = self.booth_id + "_" + remote_upload_dir

        file_defs = [
                     # Upload the HTML files to handle the continuous photos
                     [os.path.join('html', 'individual', 'index-continuous.php'), 'index', 
                      os.path.join(self.remote_file_dir, remote_upload_dir), 1, True],
                     [os.path.join('html', 'individual', 'img-continuous.php'), '', 
                      os.path.join(self.remote_file_dir, remote_upload_dir), 1, True],
                     # Make sure the base .htaccess and index files are in place
                     [os.path.join('html', 'index.php'), '', 
                      self.remote_file_dir, 1, True],
                     [os.path.join('html', 'redirect.html'), '', 
                      self.remote_file_dir, 1, True],
                     [os.path.join('html', '.htaccess'), '', 
                      self.remote_file_dir, 1, True],
                     # Make sure that all common files are in place
                     [os.path.join('html', 'common', '*'), '', 
                      os.path.join(self.remote_file_dir, 'common'), 0, True],
                    ]

        success = self.upload_photos_using_defs(file_defs)

        if success:
            return remote_upload_dir
        else:
            return None

    def upload_photo(self, filename):
        remote_upload_dir = time.strftime("%d-%b-%Y_C")
        if self.booth_id is not "":
            remote_upload_dir = self.booth_id + "_" + remote_upload_dir

        file_suffix = time.strftime("%H-%M-%S")

        file_defs = [
                     # Upload the latest photo
                     [filename, 
                      'photobooth_photo_' + file_suffix, 
                      os.path.join(self.remote_file_dir, remote_upload_dir), 1, True]
                    ]

        success = self.upload_photos_using_defs(file_defs)

        if success:
            return remote_upload_dir
        else:
            return None
class ContinuousPhotos(PhotoBoothFunction):
    'Class to continuously take photos'

    reference_photo_image = None

    def __init__(self, photobooth):
        self.menu_text = "Take continuous photos"

        self.booth_id = photobooth.get_booth_id()
        self.screen = photobooth.get_pygame_screen()
        self.filehandler = photobooth.get_file_handler()
        self.buttonhandler = photobooth.get_button_handler()

        self.local_file_dir = self.filehandler.get_local_file_dir()
        self.local_upload_file_dir = self.filehandler.get_upload_file_dir()
        self.remote_file_dir = self.filehandler.get_remote_file_dir()

        self.textprinter = TextPrinter(self.screen)
        self.imageprinter = ImagePrinter(self.screen)
        self.photohandler = PhotoHandler(self.screen, self.filehandler)

        self.total_pics = 17280  # 24 hours of a photo every 5 seconds
        self.capture_delay = 5
        self.difference_threshold = 40

    def start(self, total_pics=PhotoBoothFunction.total_pics):
        # Take and display photos
        self.total_pics = total_pics

        # Display the instructions for this photobooth function
        total_pics_msg = str(self.total_pics) + " photo"
        self.instructions = [
            "Press Start and stand out of shot",
            "so a reference photo of background", "can be taken",
            "Press the Start button to begin"
        ]
        choice = self.display_instructions()
        # If the user selected Exit, bail out
        if choice == "l":
            return

        # Set total_pics so we take our one background reference photo first
        self.set_total_pics(10000)

        self.take_photos()

    def take_photos(self):
        ################################# Step 1 - Initial Preparation ##########################
        super(ContinuousPhotos, self).take_photos()

        ################################# Step 2 - Setup camera #################################
        pixel_width = self.photo_width
        pixel_height = self.photohandler.get_aspect_ratio_height(pixel_width)

        self.camera.resolution = (pixel_width, pixel_height)

        ################################# Step 3 - Start camera preview ########################
        screen_colour_fill(self.screen, config.black_colour)

        self.camera.start_preview()

        ################################# Step 4 - Prepare the user ########################

        time.sleep(self.prep_delay_short)

        ################################# Step 5 - Take Photos ################################
        self.take_photos_and_close_camera(self.capture_delay)

    def manipulate_photo(self, filepath):
        # Use the first photo as a background reference photo
        if self.reference_photo_image is None:
            image_dir = self.filehandler.get_local_file_dir()

            # If reference_photo_image hasn't been assigned yet, then only one photo has been taken
            file_pattern = os.path.join(
                image_dir, self.photo_file_prefix + "*" + self.image_extension)
            self.reference_photo_image = Image.open(
                self.filehandler.get_sorted_file_list(file_pattern)[0])

            # Take this opportunity to upload supporting files (HTML, etc.)
            self.upload_supporting_files()
        else:
            filepath_img = Image.open(filepath)
            # Compare the new photo to the background reference photo
            rms = self.photohandler.rms_difference(filepath_img,
                                                   self.reference_photo_image)
            print "Difference to reference image: " + str(rms)

            if rms < self.difference_threshold:
                # It looks like this photo isn't very differnt to the background
                self.filehandler.delete_file(filepath)
            else:
                # It looks like this photo is very different from the background
                self.upload_photo(filepath)

    def process_photos(self):
        pass

    def upload_photos(self):
        pass

    # Create a thumbnail of the first image in the series
    def create_thumbnail(self):
        thumb_width = 200

        file_list = self.filehandler.get_sorted_file_list(
            os.path.join(self.local_file_dir, '*' + self.image_extension))
        img = self.photohandler.resize_image(file_list[0], thumb_width,
                                             thumb_width)
        img.save(
            os.path.join(self.local_file_dir,
                         'photobooth_thumb' + self.image_extension))

    def upload_supporting_files(self):
        remote_upload_dir = time.strftime("%d-%b-%Y_C")
        if self.booth_id is not "":
            remote_upload_dir = self.booth_id + "_" + remote_upload_dir

        file_defs = [
            # Upload the HTML files to handle the continuous photos
            [
                os.path.join('html', 'individual', 'index-continuous.php'),
                'index',
                os.path.join(self.remote_file_dir, remote_upload_dir), 1, True
            ],
            [
                os.path.join('html', 'individual', 'img-continuous.php'), '',
                os.path.join(self.remote_file_dir, remote_upload_dir), 1, True
            ],
            # Make sure the base .htaccess and index files are in place
            [
                os.path.join('html', 'index.php'), '', self.remote_file_dir, 1,
                True
            ],
            [
                os.path.join('html', 'redirect.html'), '',
                self.remote_file_dir, 1, True
            ],
            [
                os.path.join('html', '.htaccess'), '', self.remote_file_dir, 1,
                True
            ],
            # Make sure that all common files are in place
            [
                os.path.join('html', 'common', '*'), '',
                os.path.join(self.remote_file_dir, 'common'), 0, True
            ],
        ]

        success = self.upload_photos_using_defs(file_defs)

        if success:
            return remote_upload_dir
        else:
            return None

    def upload_photo(self, filename):
        remote_upload_dir = time.strftime("%d-%b-%Y_C")
        if self.booth_id is not "":
            remote_upload_dir = self.booth_id + "_" + remote_upload_dir

        file_suffix = time.strftime("%H-%M-%S")

        file_defs = [
            # Upload the latest photo
            [
                filename, 'photobooth_photo_' + file_suffix,
                os.path.join(self.remote_file_dir, remote_upload_dir), 1, True
            ]
        ]

        success = self.upload_photos_using_defs(file_defs)

        if success:
            return remote_upload_dir
        else:
            return None
class AnimatedPhoto(PhotoBoothFunction):
    'Class to take a series of photographs and combine them into an animated gif'

    def __init__(self, photobooth):
        self.menu_text     = "Create photo animation"

        self.booth_id      = photobooth.get_booth_id()
        self.screen        = photobooth.get_pygame_screen()
        self.filehandler   = photobooth.get_file_handler()
        self.buttonhandler = photobooth.get_button_handler()

        self.local_file_dir        = self.filehandler.get_local_file_dir()
        self.local_upload_file_dir = self.filehandler.get_upload_file_dir()
        self.remote_file_dir       = self.filehandler.get_remote_file_dir()

        self.gif_delay     = 100
        self.photo_width   = 500
        self.capture_delay = 2

        self.textprinter   = TextPrinter(self.screen)
        self.imageprinter  = ImagePrinter(self.screen)
        self.photohandler  = PhotoHandler(self.screen, self.filehandler)

    def start(self, total_pics=PhotoBoothFunction.total_pics):
        # Take and display photos
        self.total_pics = total_pics

        # Display the instructions for this photobooth function
        total_pics_msg = str(self.total_pics) + " photo"
        if self.total_pics > 1:
            total_pics_msg += "s"
        self.instructions  = [
                              total_pics_msg + " will be taken",
                              "(red light will appear before each photo)",
                              "The photos are then animated together",
                              "Press the Start button to begin"
                             ]

        # Outer loop: Instructions screen
        while True:
            choice = self.display_instructions()
            # If the user selected Exit, bail out
            if choice == "l":
                break

            while True:
                self.take_photos()

                # NOTE: If you change any part of this text display, mirror changes in erase print below
                text_rect_list = self.textprinter.print_text([["Processing. Please wait ...", 84, 
                                                               config.white_colour, "cb", 10]], 
                                                             0, False)

                # Convert the images into an animated GIF (in a separate thread)
                gif_thread = threading.Thread(target=self.process_photos)
                gif_thread.start()

                # Now display the original images one after the other in separate thread,
                #    to give the impression they are animated
                #    (easier then trying to display the animated GIF in pygame?)
                display_thread_stop = threading.Event()
                display_thread = threading.Thread(target=self.photohandler.show_photos_animated, 
                                                  args=(self.image_extension, display_thread_stop))
                display_thread.start()

                # Wait until the thread that's creating and uploading the GIF finishes
                gif_thread.join()

                # Overwrite the 'Processing' message in black to erase it
                screen_colour_fill(self.screen, config.black_colour, text_rect_list[0])
                #self.textprinter.print_text([["Processing. Please wait ...", 84, config.black_colour, "cb", 10]], 
                #                            0, False)

                # Print the button label overlays
                self.imageprinter.print_images([[config.start_overlay_image_bk_black, 'cb', 0, 0]], False)
                self.imageprinter.print_images([[config.exit_side_overlay_image_bk_black, 'lb', 0, 0]], 
                                              False)

                # Wait for the user to click Exit or Start
                choice = ""
                while True:
                    choice = self.buttonhandler.wait_for_buttons('ls', True)

                    if choice != 'screensaver':
                        break

                # Now we can stop the thread that's animating the images on the screen
                display_thread_stop.set()
                display_thread.join()

                # If user pressed Exit button, return to Photo Animation Instruction screen
                if choice == 'l':
                    break

    def take_photos(self):
        ################################# Step 1 - Initial Preparation ########################## 
        super(AnimatedPhoto, self).take_photos()

        ################################# Step 2 - Setup camera ################################# 
        pixel_width  = self.photo_width
        pixel_height = self.photohandler.get_aspect_ratio_height(pixel_width)

        self.camera.resolution = (pixel_width, pixel_height) 

        ################################# Step 3 - Start camera preview ######################## 
        screen_colour_fill(self.screen, config.black_colour)

        self.camera.start_preview()

        ################################# Step 4 - Prepare the user ########################

        time.sleep(self.prep_delay_short)

        ################################# Step 5 - Take Photos ################################ 
        self.take_photos_and_close_camera(self.capture_delay)

    def process_photos(self):
        self.combine_into_gif()
        self.create_thumbnail()
        self.upload_photos()

    # Create a thumbnail of the first image in the series
    def create_thumbnail(self):
        thumb_width = 200

        file_list = self.filehandler.get_sorted_file_list(os.path.join(self.local_file_dir, '*' + 
                                                       self.image_extension))
        img = self.photohandler.resize_image(file_list[0], thumb_width, thumb_width)
        img.save(os.path.join(self.local_file_dir, 'photobooth_thumb' + self.image_extension))

    def upload_photos(self):
        remote_upload_dir = time.strftime("%d-%b-%Y_A")
        if self.booth_id is not "":
            remote_upload_dir = self.booth_id + "_" + remote_upload_dir

        file_suffix = time.strftime("%H-%M-%S")

        file_defs = [
                     # Upload the animated GIF
                     [os.path.join(self.local_upload_file_dir, '*' + self.animated_image_extension), 
                      'photobooth_photo_' + file_suffix, 
                      os.path.join(self.remote_file_dir, remote_upload_dir), 1, True],
                     # Upload just the first of the photo files
                     [os.path.join(self.local_file_dir, 'photobooth_thumb' + self.image_extension), 
                      'photobooth_photo_' + file_suffix, 
                      os.path.join(self.remote_file_dir, remote_upload_dir), 1, True],
                     # Upload the HTML files to handle the animated photos
                     [os.path.join('html', 'individual', 'index-animated.php'), 'index', 
                      os.path.join(self.remote_file_dir, remote_upload_dir), 1, True],
                     [os.path.join('html', 'individual', 'img-animated.php'), '', 
                      os.path.join(self.remote_file_dir, remote_upload_dir), 1, True],
                     # Make sure the base .htaccess and index files are in place
                     [os.path.join('html', 'index.php'), '', 
                      self.remote_file_dir, 1, True],
                     [os.path.join('html', 'redirect.html'), '', 
                      self.remote_file_dir, 1, True],
                     [os.path.join('html', '.htaccess'), '', 
                      self.remote_file_dir, 1, True],
                     # Make sure that all common files are in place
                     [os.path.join('html', 'common', '*'), '', 
                      os.path.join(self.remote_file_dir, 'common'), 0, True],
                    ]

        success = self.upload_photos_using_defs(file_defs)

        if success:
            return remote_upload_dir
        else:
            return None

    def combine_into_gif(self):
        local_file_dir = self.filehandler.get_local_file_dir()
        print "Creating animated GIF ..."

        # Thanks to drumminhands
        graphicsmagick = ("gm convert -delay " + str(self.gif_delay) + " " + 
                             local_file_dir + "/*.jpg " + 
                             self.local_upload_file_dir + "/photobooth.gif")
        os.system(graphicsmagick) #make the .gif
class AnimatedPhoto(PhotoBoothFunction):
    'Class to take a series of photographs and combine them into an animated gif'

    def __init__(self, photobooth):
        self.menu_text = "Create photo animation"

        self.booth_id = photobooth.get_booth_id()
        self.screen = photobooth.get_pygame_screen()
        self.filehandler = photobooth.get_file_handler()
        self.buttonhandler = photobooth.get_button_handler()

        self.local_file_dir = self.filehandler.get_local_file_dir()
        self.local_upload_file_dir = self.filehandler.get_upload_file_dir()
        self.remote_file_dir = self.filehandler.get_remote_file_dir()

        self.gif_delay = 100
        self.photo_width = 500
        self.capture_delay = 2

        self.textprinter = TextPrinter(self.screen)
        self.imageprinter = ImagePrinter(self.screen)
        self.photohandler = PhotoHandler(self.screen, self.filehandler)

    def start(self, total_pics=PhotoBoothFunction.total_pics):
        # Take and display photos
        self.total_pics = total_pics

        # Display the instructions for this photobooth function
        total_pics_msg = str(self.total_pics) + " photo"
        if self.total_pics > 1:
            total_pics_msg += "s"
        self.instructions = [
            total_pics_msg + " will be taken",
            "(red light will appear before each photo)",
            "The photos are then animated together",
            "Press the Start button to begin"
        ]

        # Outer loop: Instructions screen
        while True:
            choice = self.display_instructions()
            # If the user selected Exit, bail out
            if choice == "l":
                break

            while True:
                self.take_photos()

                # NOTE: If you change any part of this text display, mirror changes in erase print below
                text_rect_list = self.textprinter.print_text([[
                    "Processing. Please wait ...", 84, config.white_colour,
                    "cb", 10
                ]], 0, False)

                # Convert the images into an animated GIF (in a separate thread)
                gif_thread = threading.Thread(target=self.process_photos)
                gif_thread.start()

                # Now display the original images one after the other in separate thread,
                #    to give the impression they are animated
                #    (easier then trying to display the animated GIF in pygame?)
                display_thread_stop = threading.Event()
                display_thread = threading.Thread(
                    target=self.photohandler.show_photos_animated,
                    args=(self.image_extension, display_thread_stop))
                display_thread.start()

                # Wait until the thread that's creating and uploading the GIF finishes
                gif_thread.join()

                # Overwrite the 'Processing' message in black to erase it
                screen_colour_fill(self.screen, config.black_colour,
                                   text_rect_list[0])
                #self.textprinter.print_text([["Processing. Please wait ...", 84, config.black_colour, "cb", 10]],
                #                            0, False)

                # Print the button label overlays
                self.imageprinter.print_images(
                    [[config.start_overlay_image_bk_black, 'cb', 0, 0]], False)
                self.imageprinter.print_images(
                    [[config.exit_side_overlay_image_bk_black, 'lb', 0, 0]],
                    False)

                # Wait for the user to click Exit or Start
                choice = ""
                while True:
                    choice = self.buttonhandler.wait_for_buttons('ls', True)

                    if choice != 'screensaver':
                        break

                # Now we can stop the thread that's animating the images on the screen
                display_thread_stop.set()
                display_thread.join()

                # If user pressed Exit button, return to Photo Animation Instruction screen
                if choice == 'l':
                    break

    def take_photos(self):
        ################################# Step 1 - Initial Preparation ##########################
        super(AnimatedPhoto, self).take_photos()

        ################################# Step 2 - Setup camera #################################
        pixel_width = self.photo_width
        pixel_height = self.photohandler.get_aspect_ratio_height(pixel_width)

        self.camera.resolution = (pixel_width, pixel_height)

        ################################# Step 3 - Start camera preview ########################
        screen_colour_fill(self.screen, config.black_colour)

        self.camera.start_preview()

        ################################# Step 4 - Prepare the user ########################

        time.sleep(self.prep_delay_short)

        ################################# Step 5 - Take Photos ################################
        self.take_photos_and_close_camera(self.capture_delay)

    def process_photos(self):
        self.combine_into_gif()
        self.create_thumbnail()
        self.upload_photos()

    # Create a thumbnail of the first image in the series
    def create_thumbnail(self):
        thumb_width = 200

        file_list = self.filehandler.get_sorted_file_list(
            os.path.join(self.local_file_dir, '*' + self.image_extension))
        img = self.photohandler.resize_image(file_list[0], thumb_width,
                                             thumb_width)
        img.save(
            os.path.join(self.local_file_dir,
                         'photobooth_thumb' + self.image_extension))

    def upload_photos(self):
        remote_upload_dir = time.strftime("%d-%b-%Y_A")
        if self.booth_id is not "":
            remote_upload_dir = self.booth_id + "_" + remote_upload_dir

        file_suffix = time.strftime("%H-%M-%S")

        file_defs = [
            # Upload the animated GIF
            [
                os.path.join(self.local_upload_file_dir,
                             '*' + self.animated_image_extension),
                'photobooth_photo_' + file_suffix,
                os.path.join(self.remote_file_dir, remote_upload_dir), 1, True
            ],
            # Upload just the first of the photo files
            [
                os.path.join(self.local_file_dir,
                             'photobooth_thumb' + self.image_extension),
                'photobooth_photo_' + file_suffix,
                os.path.join(self.remote_file_dir, remote_upload_dir), 1, True
            ],
            # Upload the HTML files to handle the animated photos
            [
                os.path.join('html', 'individual', 'index-animated.php'),
                'index',
                os.path.join(self.remote_file_dir, remote_upload_dir), 1, True
            ],
            [
                os.path.join('html', 'individual', 'img-animated.php'), '',
                os.path.join(self.remote_file_dir, remote_upload_dir), 1, True
            ],
            # Make sure the base .htaccess and index files are in place
            [
                os.path.join('html', 'index.php'), '', self.remote_file_dir, 1,
                True
            ],
            [
                os.path.join('html', 'redirect.html'), '',
                self.remote_file_dir, 1, True
            ],
            [
                os.path.join('html', '.htaccess'), '', self.remote_file_dir, 1,
                True
            ],
            # Make sure that all common files are in place
            [
                os.path.join('html', 'common', '*'), '',
                os.path.join(self.remote_file_dir, 'common'), 0, True
            ],
        ]

        success = self.upload_photos_using_defs(file_defs)

        if success:
            return remote_upload_dir
        else:
            return None

    def combine_into_gif(self):
        local_file_dir = self.filehandler.get_local_file_dir()
        print "Creating animated GIF ..."

        # Thanks to drumminhands
        graphicsmagick = ("gm convert -delay " + str(self.gif_delay) + " " +
                          local_file_dir + "/*.jpg " +
                          self.local_upload_file_dir + "/photobooth.gif")
        os.system(graphicsmagick)  #make the .gif