import os
import cv2
import numpy as np
import csv
from pathlib import Path
from datetime import datetime
import sys
import subprocess


def compare_image(image_1, image_2):
    # start_time = time.time()
    first_image_hist = cv2.calcHist([image_1], [0], None, [256], [0, 256])
    second_image_hist = cv2.calcHist([image_2], [0], None, [256], [0, 256])
    img_hist_diff = cv2.compareHist(first_image_hist, second_image_hist, cv2.HISTCMP_BHATTACHARYYA)
    img_template_probability_match = cv2.matchTemplate(first_image_hist, second_image_hist, cv2.TM_CCOEFF_NORMED)[0][0]
    img_template_diff = 1 - img_template_probability_match
    commutative_image_diff = (img_hist_diff * 0.75) + img_template_diff
    # end_time = time.time()
    return commutative_image_diff


def mse(imageA, imageB):
    err = np.sum((imageA.astype("float") - imageB.astype("float")) ** 2)
    err /= float(imageA.shape[0] * imageA.shape[1])
    return err

def similarity(img1, img2, threshold=500):
    error = mse(img1, img2)
    return error < threshold

from datetime import datetime

def timestamp_to_datetime(timestamp):
    return datetime.fromtimestamp(timestamp)

def extract_timestamp(filename):
    timestamp = filename.split("_")[0]
    timestamp = timestamp.split(".")[1]
    # timestamp = timestamp[13:]
    return int(timestamp)


day_iframe_folder = str(sys.argv[1])
ads_folder = "ads"
# day_iframe_folder = "day_iframes"
output_csv = day_iframe_folder+".csv"

# Load all ads into memory and organize them in a dictionary
ads_dict = {}
for brand in os.listdir(ads_folder):
    print("brand: "+brand)
    brand_path = os.path.join(ads_folder, brand)
    if os.path.isdir(brand_path):
        ads_dict[brand] = {}
        for ad in os.listdir(brand_path):
            print("ad: "+ad)
            if ad.endswith(".png"):
                ad_path = os.path.join(brand_path, ad)
                # ad_img = cv2.imread(ad_path, cv2.IMREAD_GRAYSCALE)
                ad_img = cv2.imread(ad_path)
                product = ad.split("_")[1]
                if product not in ads_dict[brand]:
                    ads_dict[brand][product] = []
                ads_dict[brand][product].append({"filename": ad, "image": ad_img})

# day_iframes = [filename for filename in os.listdir(day_iframe_folder) if filename.endswith(".png")]
day_iframes = sorted([filename for filename in os.listdir(day_iframe_folder) if filename.endswith(".png")])


with open(output_csv, mode="w", newline="") as csvfile:
    csv_writer = csv.writer(csvfile)
    csv_writer.writerow(["Brand", "Product", "Ad_Iframe", "Day_Iframe", "Timestamp"])

    # prev_brand = None
    # prev_timestamp = None
    #
    # for day_iframe in day_iframes:
    #     day_iframe_path = os.path.join(day_iframe_folder, day_iframe)
    #     day_img = cv2.imread(day_iframe_path)
    #
    #     for brand in ads_dict:
    #         for product in ads_dict[brand]:
    #             for ad in ads_dict[brand][product]:
    #                 ad_img = ad["image"]
    #                 if compare_image(ad_img, day_img)<0.1:
    #                     timestamp = extract_timestamp(day_iframe)
    #                     dt_object = datetime.fromtimestamp(timestamp)
    #
    #                     if prev_brand == brand and prev_timestamp is not None and (dt_object - prev_timestamp).total_seconds() < 300:
    #                         # Skip this row if the same brand and the timestamp is less than 5 minutes apart from the last one
    #                         continue
    #
    #                     csv_writer.writerow([brand, product, ad["filename"], day_iframe, dt_object])
    #
    #                     # Update the previous brand and timestamp
    #                     prev_brand = brand
    #                     prev_timestamp = dt_object

    for day_iframe in day_iframes:
        # if day_iframe == "index202304151681509601_15_27_6.png":
        #     print("====================================================")

        # print("day_iframe: "+day_iframe)
        day_iframe_path = os.path.join(day_iframe_folder, day_iframe)
        # day_img = cv2.imread(day_iframe_path, cv2.IMREAD_GRAYSCALE)
        day_img = cv2.imread(day_iframe_path)

        for brand in ads_dict:
            for product in ads_dict[brand]:
                for ad in ads_dict[brand][product]:
                    ad_img = ad["image"]
                    # print("compare_image: "+str(compare_image(ad_img, day_img)))
                    if compare_image(ad_img, day_img)<0.1:
                        print("//////////////////////////////////")
                        print("//////////////////////////////////")
                        print("//////////////////////////////////")
                        print("ad_img: "+ad["filename"])
                        print("day_iframe: "+day_iframe)
                        timestamp = extract_timestamp(day_iframe)
                        print("timestamp: "+str(timestamp_to_datetime(int(timestamp))))

                        dt_object = datetime.fromtimestamp(timestamp)
                        csv_writer.writerow([brand, product, ad["filename"], day_iframe, dt_object])
                        # exit()
