import pandas as pd
import numpy as np
import os
import re
import json
import datetime

os.environ["OPENCV_LOG_LEVEL"] = "OFF"
import cv2
from src.scrape_api import get_ids


def map_image(img_path, row, signature_to_id, signature):
    img = cv2.imread(img_path)
    # h, w = img.shape[0:2]
    # neww = 800
    # newh = int(neww * (h / w))
    # img = cv2.resize(img, (neww, newh))
    cv2.imshow(f'{img_path}', img)
    key = cv2.waitKey(0) & 0xFF
    while True:
        # KEYBOARD INTERACTIONS
        if key == ord('q'):
            cv2.destroyAllWindows()
            return 'q'
        elif key == ord('y'):
            # Associate current image with article information
            cv2.destroyAllWindows()
            return 'y'
        elif key == ord('n'):
            # Do not associate current image with article information
            cv2.destroyAllWindows()
            return 'n'
        elif key == ord('b'):
            cv2.destroyAllWindows()
            return 'b'
        elif key == ord('f'):
            cv2.destroyAllWindows()
            return 'f'
        elif key == ord('u'):
            cv2.destroyAllWindows()
            return 'u'
        elif key == ord('j'):
            cv2.destroyAllWindows()
            return 'j'
        elif key == ord('r'):
            cv2.destroyAllWindows()
            return 'r'
        elif key == ord('+'):
            cv2.destroyAllWindows()
            img = cv2.resize(img, None, fx=1.2, fy=1.2)
            cv2.imshow(f'{img_path}', img)
            key = cv2.waitKey(0) & 0xFF
        elif key == ord('-'):
            cv2.destroyAllWindows()
            img = cv2.resize(img, None, fx=0.8, fy=0.8)
            cv2.imshow(f'{img_path}', img)
            key = cv2.waitKey(0) & 0xFF


if __name__ == '__main__':
    # Get a dictionary with the signature -> ID mapping
    signature_to_id = get_ids(signatures=True)[1]
    id_to_signature = {v: k for k, v in signature_to_id.items()}

    signatures = pd.read_csv('../datasets/signatures.csv', delimiter=';')[:-1]
    signatures['Foliujo'] = signatures['Foliujo'].astype(int)
    folders_dir = '../artifacts/folders-cleaned'

    csv_files = [f for f in os.listdir(folders_dir) if f.endswith('.csv')]

    signature_to_df = {}
    for file in csv_files:
        file_path = os.path.join(folders_dir, file)
        df = pd.read_csv(file_path, delimiter=';', dtype={'Images': str})
        signature = id_to_signature[os.path.splitext(file)[0]]
        signature_to_df[signature] = df

    for signature in signature_to_df:
        print(f'Sig:\t{signature}\nID:\t{signature_to_id[signature]}')
        # Index to save current position in image paths
        idx = 0
        rows = list(signature_to_df[signature].itertuples())
        row_idx = 0
        skip_folder = False
        reverse = False
        reverse_ctr = 0
        i = 0
        while row_idx < len(rows):
            # Set row.Images to empty string
            row = rows[row_idx]
            signature_to_df[signature].at[row.Index, 'Images'] = ""
            # Save current row information to file which is watched
            current_info = f'Number:\t{row.Index}\nTitle:\t{row.Titolo}\nAuthor:\t{row.Verkinto}\nDate:\t{row.Dato}\nMag:\t{row.Revuo}\n\n'
            next_row = rows[(row_idx + 1) % len(rows)]
            next_info = f'Number:\t{next_row.Index}\nTitle:\t{next_row.Titolo}\nAuthor:\t{next_row.Verkinto}\nDate:\t{next_row.Dato}\nMag:\t{next_row.Revuo}'
            with open('current.txt', 'w') as f:
                f.write(current_info)
                f.write(next_info)

            # Get all image paths to loop over
            id_path = f'/home/zenon/Documents/esperanto/datasets/images/{signature_to_id[signature]}'
            imgs = os.listdir(id_path)
            imgs.sort()
            imgs = list(map(lambda x: id_path + '/' + x, imgs))
            associated_img_paths = []

            if not reverse:
                i = idx
                while i < len(imgs):
                    img_path = imgs[i]
                    if i < idx:
                        continue
                    i = i + 1
                    action = map_image(img_path, row, signature_to_id, signature)
                    if action == 'y':
                        # If image belongs to article, append it
                        associated_img_paths.append(img_path)
                        idx = i
                    elif action == 'n':
                        idx = i
                        continue
                    elif action == 'f':
                        continue
                    elif action == 'b':
                        i = i - 2
                        idx = i
                        continue
                    elif action == 'u':
                        i = i - 2
                        idx = i
                        row_idx = row_idx - 2
                        break
                    elif action == 'j':
                        skip_folder = True
                        break
                    elif action == 'r':
                        # Reverse through images
                        reverse_ctr = 1
                        reverse = True
                        idx = len(imgs) - 1
                        break
                    else:
                        idx = i - 1
                        break
            else:
                i = idx
                while i >= 0:
                    img_path = imgs[i]
                    if i > idx:
                        continue
                    action = map_image(img_path, row, signature_to_id, signature)
                    if action == 'y':
                        # If image belongs to article, append it
                        associated_img_paths.append(img_path)
                        i = i - 1
                        idx = i
                    elif action == 'n':
                        i = i - 1
                        idx = i
                        continue
                    elif action == 'f':
                        i = i - 1
                        idx = i
                        continue
                    elif action == 'b':
                        i = i + 1
                        idx = i
                        continue
                    elif action == 'u':
                        i = i + 1
                        idx = i
                        row_idx = row_idx - 2
                        break
                    elif action == 'j':
                        skip_folder = True
                        break
                    elif action == 'r':
                        # Reverse through images
                        reverse = False
                        break
                    else:
                        idx = i
                        break

            if skip_folder:
                break
            signature_to_df[signature].at[row.Index, 'Images'] = ','.join(
                associated_img_paths)
            os.makedirs('../artifacts/mapping', exist_ok=True)
            signature_to_df[signature].to_csv(
                f'../artifacts/mapping/{signature_to_id[signature]}.csv',
                sep=';',
                index=False)
            if reverse_ctr == 1:
                reverse_ctr = 2
                idx = len(imgs) - 1
                i = idx
            else:
                row_idx = row_idx + 1
                reverse_ctr = 0
        print(signature_to_df[signature])
