"""
This code runs lane detection based on
Computer Vision, perspective transformation,
and polynomial fit
"""
from resolution_adjust import crop_img
from transformation import perspective_transform
from line_fit import line_fit, final_viz
import cv2
import cupy as cp
import time


# Read camera capture
loop_time = 100
# Initialize camera or video file
cap = cv2.VideoCapture("video_test.mp4")
t_old = 0

while True:
    t_act = time.time() * 1000
    if t_act - t_old > loop_time:

        self_ret, image = cap.read()
        if not self_ret:
            break

        t0 = time.time()
        canny, croped, gray = crop_img(image)
        t1 = time.time()
        binary_warped, m, m_inv = perspective_transform(canny)
        t2 = time.time()
        c_binary_warped = cp.asarray(binary_warped)
        c_ret = line_fit(c_binary_warped)
        t3 = time.time()
        c_left_fit = c_ret['left_fit']
        c_right_fit = c_ret['right_fit']
        t4 = time.time()

        result, newwarp = final_viz(croped, c_left_fit, c_right_fit, m_inv)
        t5 = time.time()
        # Uncoment to draw an image
        # cv2.imshow("image", image)
        # cv2.imshow("gray", gray)
        # cv2.imshow("Canny", canny)
        # cv2.imshow("crop", croped)
        cv2.imshow("binary_warped", binary_warped)
        cv2.imshow("result", result)
        if t_act - t_old - 1 < loop_time:
            print("The image have been updated", t_act - t_old)
        else:
            print("ERROR the time was longer", t_act - t_old)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        t_old = t_act

cap.release()
cv2.destroyAllWindows()
