from pioneer_sdk import Pioneer
import os
import sys
import math
import cv2
import cv2.aruco as aruco
import numpy as np
import yaml
import multiprocessing as mp
import time
from multiprocessing.managers import BaseManager


def image_proc(buff, drone, camera_mtx, camera_dist):
    size_of_marker = 0.10  # side length in meters
    aruco_dict = aruco.Dictionary_get(aruco.DICT_4X4_50)
    aruco_parameters = aruco.DetectorParameters_create()
    while True:
        try:
            camera_frame = cv2.imdecode(np.frombuffer(drone.get_raw_video_frame(), dtype=np.uint8),
                                        cv2.IMREAD_COLOR)
            gray = cv2.cvtColor(camera_frame, cv2.COLOR_BGR2GRAY)
            corners, ids, rejected_img_points = aruco.detectMarkers(gray, aruco_dict, parameters=aruco_parameters)
            aruco.drawDetectedMarkers(camera_frame, corners)
            if (ids is not None):
                for i in range(len(ids)):
                    #print(i)
                    #print(corners[i])
                    #print(ids[i])
                    #if np.all(ids is not None):
                    r_vec_rodrigues, t_vec, _ = aruco.estimatePoseSingleMarkers(corners[i], size_of_marker, camera_mtx, camera_dist)
                    #aruco.drawAxis(camera_frame, camera_mtx, camera_dist, r_vec_rodrigues, t_vec, 0.01)

                    r_mat = cv2.Rodrigues(r_vec_rodrigues)[0]
                    #p = np.hstack((r_mat.reshape(3, 3), t_vec.reshape(3, 1)))
                    r_vec_euler = corners[i]
                    if buff.full():
                        buff.get()
                    buff.put([t_vec, r_vec_euler, ids[i]])

        except cv2.error:
            continue

        cv2.imshow('marker_detection', camera_frame)
        key = cv2.waitKey(1)

        if key == 27:  # esc
            print('esc pressed')
            cv2.destroyAllWindows()
            if buff.full():
                buff.get()
            buff.put(['end'])
            drone.led_control(led_id=255, r=0, g=0, b=0)
            break


def drone_control(buff, drone):

    Finish_task = [[0.8, 0, 1, 99]  # Координаты финишного задания относительно положения дрона [x, y, z]

                   ]
    Start_task = [[-0.8, 0, 1, 99],  # Координаты стартового задания относительно положения дрона  [x, y, z]

                  ]
    task = [[0, 2.2, 0.7, 88],
            [0.7, 1, 0.7, 88],
            [0, 0, 1.9, 99],
            [0.2, 1.1, 1.9, 88],
            [1.5, 0.6, 1, 99],
            [-0.7, 0, 0.7, 88],
            [0, 0, 1.8, 99],
            [-0.9, 0, 1.8, 88],
            [0.5, -2.4, 1.3, 88],
            [1.4, -2.1, 1.3, 88]
            [0, -1.2, 1.3, 99],
            [-2, 0, 1.3, 99]




            ]

    command_x = float(0)
    command_y = float(0)
    command_z = float(1)  # initial flight height
    command_yaw = math.radians(float(0))

    k_p_xy = 0.4
    ti = 0
    tt = 0
    tf = 0
    l = 1
    Laps = 1  # Количество кругов
    t_vec = None
    new_point = True
    new_message = True

    p_r = False
    m_r = False
    start = True
    finish = False
    pointN = 99
    pointE = 88

    while True:
        if new_point and new_message:
            print('Drone go to local point', command_x, command_y)
            drone.go_to_local_point(x=command_x, y=command_y, z=command_z, yaw=command_yaw)
            new_point = False
            new_message = False
            drone.led_control(led_id=255, r=0, g=180, b=0)

        if not buff.empty():
            message = buff.get()
            if len(message) == 1 and message[0] == 'end':
                break
            t_vec = message[0]
            r_vec_euler = message[1]
            ids = message[2]
            print(ids, pointN)
            new_message = True
            #if pointN == ids :
             #   new_message = True


        if drone.point_reached():
            p_r = True
            drone.led_control(led_id=255, r=0, g=0, b=180)

            if start:  # Стартовое задание (Выполняется до полётного задания)
                if tt >= len(Start_task):
                    tt = 0
                    print('Start finished')
                    start = False
                else:
                    command_x += Start_task[tt][0]
                    command_y += Start_task[tt][1]
                    command_z = Start_task[tt][2]
                    pointN = Start_task[tt][3]
                    tt += 1
                    new_point = True
                    new_message = True
                    p_r = False
                    m_r = False
                    print('Start task point')

            if finish:  # Финишное задание (Выполняется после полётного задания)
                if tf >= len(Finish_task):
                    print('Landing task ended')
                    drone.led_control(led_id=255, r=0, g=0, b=0)
                    break
                else:
                        command_x += Finish_task[tf][0]
                        command_y += Finish_task[tf][1]
                        command_z = Finish_task[tf][2]
                        pointN = Finish_task[tf][3]
                        tf += 1
                        new_point = True
                        new_message = True
                        p_r = False
                        m_r = False
                        print('Finish task point')

            if not start and not finish:  # Полётное задание
                if ti >= len(task):
                    l += 1
                    ti = 0
                    print('New loop')
                else:
                    pointN = task[ti][3]
                    if task[ti][3] == 99 or m_r:
                        command_x += task[ti][0]
                        command_y += task[ti][1]
                        command_z = task[ti][2]
                        ti += 1
                        new_point = True
                        new_message = True
                        p_r = False
                        m_r = False
                        print('New task point')
                        drone.led_control(led_id=255, r=0, g=180, b=0)

        if l > Laps :  
            finish = True

        if p_r and t_vec is not None and (pointN == ids or pointN == pointE):
            x_camera = t_vec.item(0)
            y_camera = t_vec.item(1)
            print('Find marker!', ids)
            if ids == pointN or pointN == pointE:
                if abs(x_camera) < 0.13 and abs(y_camera) < 0.13:  # Калибровка над маркером
                    m_r = True
                    print('Marker reached!')
                    drone.led_control(led_id=255, r=180, g=0, b=0)

                else:
                    command_yaw = 0
                    command_x += k_p_xy*(x_camera)
                    command_y -= k_p_xy*(y_camera)
                    print('Calibrating...')
                    if not m_r and p_r and not new_point and not new_message:  # Поиск маркера
                        drone.led_control(led_id=255, r=180, g=180, b=180)
                        print('Search...')
                        drone.go_to_local_point(x=command_x, y=command_y, z=2, yaw=command_yaw)
                        while not drone.point_reached():
                            a = 1

                new_point = True
                p_r = False
            #else:
                #if not buff.empty():
                    #message = buff.get()
                    #if len(message) == 1 and message[0] == 'end':
                        #break
                   # t_vec = message[0]
                    #r_vec_euler = message[1]
                   # ids = message[2]
                    #new_message = True


if __name__ == '__main__':
    print('start')
    try:
        calibration_file = open(os.path.join(os.getcwd(), '..', "camera_calibration", "result",
                                             "calibration_matrix.yaml"))
        parsed_calibration_file = yaml.load(calibration_file, Loader=yaml.FullLoader)
        mtx = np.array(parsed_calibration_file.get("camera_matrix"))
        dist = np.array(parsed_calibration_file.get("dist_coeff"))
    except FileNotFoundError:
        print('Сan not find calibration data, please run get_camera_samples.py script from camera calibration folder')
        sys.exit(0)
    BaseManager.register('Pioneer', Pioneer)
    manager = BaseManager()
    manager.start()
    pioneer_mini = manager.Pioneer()
    pioneer_mini.arm()
    pioneer_mini.takeoff()
    #time.sleep(5)

    buffer = mp.Queue(maxsize=1)
    pos_and_orient = mp.Process(target=image_proc, args=(buffer, pioneer_mini, mtx, dist))
    drone_flight = mp.Process(target=drone_control, args=(buffer, pioneer_mini))
    pos_and_orient.start()
    drone_flight.start()


    drone_flight.join()

    pioneer_mini.land()
