from pathlib import Path
import fnmatch
import os
import cv2
import math
import numpy

# SETTINGS ###################################################################################
# path of images folder
path_images = Path(r"")
# path of labels folder
path_labels = Path(r"")
# path of destination folder (for parameters)
path_parameters = Path(r"")
##############################################################################################


# get all files of defined type from folder
def listdir(dir_name, pattern="*"):
    return fnmatch.filter(os.listdir(dir_name), pattern)


# parameters based on label: class, area, number of object (class and area of biggest object)
def get_parameters_based_on_label(path_of_folder, name_of_file):
    # opening text file
    label_file = open(str(path_of_folder) + '/' + str(name_of_file), "r")

    # parameters
    par_class = 0
    par_area = 0
    par_number = 0

    # reading line
    line = label_file.readline()
    while len(line) > 3:
        line_strip = str.rstrip(line)
        list_line = line_strip.split(" ")
        # print(list_line)
        line = label_file.readline()

        # number of objects
        par_number += 1
        # area of current object
        area = float(list_line[3]) * float(list_line[4])
        # searching for bigger object
        if area > par_area:
            # area of biggest object
            par_area = area
            # class of biggest object
            par_class = int(list_line[0])
    # boundaries for dividing area (can be modified later)
    if par_area > 0.013:
        par_area = 2
    elif par_area > 0.005:
        par_area = 1
    else:
        par_area = 0
    # one or zeros object -> par_number = 0; more then one -> par number = 1
    if par_number > 1:
        par_number = 1
    else:
        par_number = 0
    # closing file
    label_file.close()
    return par_class, par_area, par_number


def get_parameters_of_weather_and_complexity(path_folder, name_of_file):
    img = cv2.imread(str(path_folder)+'/'+name_of_file, flags=cv2.IMREAD_COLOR)
    print(name_of_file)
    val = numpy.reshape(img[:, :, 0], -1)
    std = numpy.std(val)
    print("std: " + str(std))
    if std <= 31:
        par_complexity = 0
    else:
        par_complexity = 1
    crop_img = img[0:math.ceil((len(img) / 2)), 0:len(img[0])]
    crop_img_rgb = cv2.split(crop_img)
    avg_hist = sum(numpy.ravel(crop_img_rgb[2]))/len(numpy.ravel(crop_img_rgb[2]))
    print("Average_hist blue: "+str(avg_hist))
    print("")
    if avg_hist <= 107.0:
        par_weather = 0
    else:
        par_weather = 1

    return par_complexity, par_weather


# GET DATA ###################################################################################
# find all labels and images in path folder
labels_array = listdir(str(path_labels), "*.txt")
images_array = listdir(str(path_images), "*.jpg")

# names of images and labels must be the same
valid = 1
if len(labels_array) == len(images_array):
    for i in range(len(labels_array)):
        name1 = labels_array[i][:-4]
        name2 = images_array[i][:-4]
        if name1 != name2:
            valid = 0
            break
else:
    valid = 0

if valid == 1:
    print("Name arrays of images and labels are the same => valid.")
else:
    print("Name arrays of images and labels are not the same => invalid.")
##############################################################################################

if valid:
    # GET PARAMETERS #########################################################################
    for i in range(len(labels_array)):
        # getting parameters from labels (class, area, number of objects)
        p_class, p_area, p_number = get_parameters_based_on_label(path_labels, labels_array[i])
        # getting information about weather and complexity
        p_complexity, p_weather = get_parameters_of_weather_and_complexity(path_images, images_array[i])

        # crate files with parameters in name
        name = labels_array[i][:-4]
        # print(name)
        str_params = str(p_class) + str(p_complexity) + str(p_area) + str(p_number) + str(p_weather)
        text_file = open(str(path_parameters) + '/' + name + '_' + str_params + ".txt", "w")
        text_file.close()

        # write parameters
        '''
        print("class: " + str(p_class) + " complexity: " + str(p_complexity) + " area: " + str(p_area) +
              "  number_of_object: " + str(p_number) + " weather: " + str(p_weather))
        '''
##############################################################################################
