#!/usr/bin/python3

import sys, os, time
PACKAGE_DIR = os.path.abspath(os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))))
sys.path.insert(0, PACKAGE_DIR)

from PyQt5 import QtCore
from mainWindow import StartQT5
from pytestqt.qt_compat import qt_api
import pytest
from PIL import Image
import numpy as np
from io import BytesIO
from cv2 import imread, imdecode, IMREAD_COLOR
from scipy.linalg import norm
from numpy import sum, average

"""
the code to compare two images was taken from
https://gist.github.com/astanin/626356
Many thanks to the author: Sergey Astanin <https://gist.github.com/astanin>
"""

def compare_images(img1, img2):
    # normalize to compensate for exposure difference
    img1 = normalize(img1)
    img2 = normalize(img2)
    # calculate the difference and its norms
    diff = img1 - img2  # elementwise for scipy arrays
    m_norm = sum(abs(diff))  # Manhattan norm
    z_norm = norm(diff.ravel(), 0)  # Zero norm
    return (m_norm, z_norm)

def to_grayscale(arr):
    "If arr is a color image (3D array), convert it to grayscale (2D array)."
    if len(arr.shape) == 3:
        return average(arr, -1)  # average over the last axis (color channels)
    else:
        return arr

def normalize(arr):
    rng = arr.max()-arr.min()
    amin = arr.min()
    return (arr-amin)*255/rng

@pytest.mark.skipif(platform.machine() != 'x86_64',
                    reason="architecture is not amd64")
def test_earth(qtbot):
    mw = StartQT5(None)
    mw.show()
    qtbot.addWidget(mw)
    mw.ui.vitesse_tangentielle_objet.setText("-7400")
    qtbot.mouseClick(mw.ui.Bouton_Lancer, QtCore.Qt.LeftButton)
    time.sleep(3)
    figureCanvas = mw.ui.label_vitx.children()[0]
    buffer = BytesIO()
    figureCanvas.fig.savefig(buffer)
    buffer.seek(0)
    file_bytes = np.asarray(bytearray(buffer.read()), dtype=np.uint8)
    img1 = to_grayscale(imdecode(file_bytes, IMREAD_COLOR).astype(float))
    img2 = to_grayscale(imread(
        os.path.join(
            PACKAGE_DIR, "debian", "tests", "gui_vitx.png")).astype(float))
    manhattan_norm, zero_norm = compare_images(img1, img2)
    qt_api.qWarning(f"Manhattan_norm {manhattan_norm}, Zero norm {zero_norm}")
    assert(manhattan_norm == 0)
    assert(zero_norm == 0)
