##  @package test_omx
#   Test omxplayer with E2 camera.
#
#   @author     Mark Zvilius
#   @date       22-Feb-2020
#   @copyright  Virtual Reality Technology Underwater Limited (VRTUL)
#
import sys
import E2Configs
from E2Camera import E2Camera
from omxplayer.player import OMXPlayer

CAMERA_IP = '10.6.10.161'
STREAM_SETTINGS = {'width':'960', 'height':'540', 'bitrate':'500000', 'fps':'30'}

##  Video position (upper left corner) and size in pixels.
VIDEO_POSITION = (480,0)
VIDEO_SIZE = (960,540)

class VideoWindow:
    def __init__(self, size, position, camera):
        self._rtsp_url = ''
        self._player = None
        self._ul_x = position[0]
        self._ul_y = position[1]
        self._lr_x = self._ul_x + size[0]
        self._lr_y = self._ul_y + size[1]
        self._streaming_args = []
        self._cam = camera

    def set_streaming_args(self, args):
        self._streaming_args = args

    def is_running(self):
        return self._player is not None

    def go(self):
        self._rtsp_url = f'rtsp://{cam.ip}/live_stream'
        self.stop()
        self._start()
        print(f'cam {cam.id}')
        return cam.id

    def _start(self):
        assert(not self.is_running())

        try:
            self._player = OMXPlayer(self._rtsp_url, args=self._streaming_args)
            self._player.set_video_pos(self._ul_x, self._ul_y, self._lr_x, self._lr_y)
            self._player.set_aspect_mode('letterbox')
        except Exception as err:
            self._player = None
            print('exception:', err)

    def stop(self):
        if self.is_running():
            self._player.quit()
            self._player = None


if __name__ == '__main__':
    print('hello world')

    # Read the config files.
    # An exception is fatal.
    try:
        E2Configs.load()
    except:
        print('failed to load config files:', sys.exc_info()[1])
        exit(1)

    cam = E2Camera(CAMERA_IP, 'Z', master=True)
    (status,errmsg) = cam.start_camera(E2Configs.camera_settings)
    if status != 0:
        print(errmsg)
        exit(1)

    (status,errmsg) = cam.command_stream_settings('stream1', STREAM_SETTINGS)
    if status != 0:
        print(errmsg)
        exit(1)

    video = VideoWindow(size=VIDEO_SIZE, position=VIDEO_POSITION, camera=cam)
    video.set_streaming_args(E2Camera.OMXPLAYER_ARGS)
    camera_id = video.go()

    input('press enter to exit')
    video.stop()
    
    print('goodbye')
