'''
Created on Jan 11, 2022

@author: nathanielc

python file located in the Image Compression project
folder under nathanielc user. This python file is for
exploring possible image compression techniques and is by 
no means a final product. Goal is to learn how to download 
images and extract important statistics from them.
'''

import numpy as np
from matplotlib import pyplot as plt
from itertools import product
import os
import sys
from PIL import Image


def file_extractor(dirname="images"):
    files = os.listdir(dirname)
    scenes = []
    for file in files:
        scenes.append(os.path.join(dirname, file))
    return scenes

def image_extractor(scenes):
    image_folder = []
    for scene in scenes:
        files = os.listdir(scene)
        for file in files:
            image_folder.append(os.path.join(scene, file))
    images = []
    for folder in image_folder:
        ims = os.listdir(folder)
        for im in ims:
            if im[-4:] == ".jp4" or im[-7:] == "_6.tiff":
                continue
            else:
                images.append(os.path.join(folder, im))
    return images #returns a list of file paths to .tiff files in the specified directory given in file_extractor

def im_distribution(images, num):
    """
    Function that extracts tiff files from specific cameras and returns a list of all
    the tiff files corresponding to that camera. i.e. all pictures labeled "_7.tiff" or otherwise
    specified camera numbers.
    
    Parameters:
        images (list): list of all tiff files, regardless of classification. This is NOT a list of directories but
        of specific tiff files that can be opened right away. This is the list that we iterate through and 
        divide.
        
        num (str): a string designation for the camera number that we want to extract i.e. "14" for double digits
        of "_1" for single digits.
        
    Returns:
        tiff (list): A list of tiff files that have the specified designation from num. They are the files extracted
        from the 'images' list that correspond to the given num.
    """
    tiff = []
    for im in images:
        if im[-7:-6] == num:
            tiff.append(im)
    return tiff
    
    
def plot_hist(tiff_list):
    """
    This function is the leftovers from the first attempt to plot histograms.
    As it stands it needs some work in order to function again. We will
    fix this later. 1/25/22
    """
    jj = 0
    fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(15,12))
    for cam, ax in zip(cameras, axs.ravel()):
        diff = []
        for ii in range(len(cam)):
            image = Image.open(cam[ii])    #Open the image and read it as an Image object
            image = np.array(image)[1:,:]    #Convert to an array, leaving out the first row because the first row is just housekeeping data
            ar1, ar2 = image.shape
           
            ind1, ind2 = np.random.randint(1,ar1-1), np.random.randint(1,ar2-1) #ind1 randomly selects a row, ind2 randomly selects a column, 
                                                                            #this is now a random pixel selection within the image
            
            surrounding = []                                                #initialize a list to be filled the 8 surrounding pixels
            for i,j in product(np.arange(-1,2), repeat=2):                  #Iterate through the combinations of surrounding pixel indices
                if i == 0 and j == 0:                                       #Avoid the target pixel
                    continue
                else:
                    surrounding.append(image[ind1+i, ind1+j])               #Add the other 8 pixels to the list
            diff.append(np.max(surrounding)-np.min(surrounding))
        ax.hist(diff)
        ax.set_title(f"tiff {jj}")
        jj += 1
    plt.tight_layout()
    plt.show()
    return 

if __name__ == '__main__':

    """For boundary cases: Start by grabbing the shape of the images and saving those
    as variables. Then, if statements for if row == 0 or row == maximum and if
    col == 0 or col == maximum. Then grab corresponding open pixels. Then proceed to do
    an and statement that handles the corners"""
    
    
    scenes = file_extractor()
    images = image_extractor(scenes)
    
    