#!/usr/bin/python
import ujson
import os

from edge.com import fs
from edge import path_helpers as ph


_PIPELINE_SET_FILEPATH = '/etc/edge/setupstore/admin/actions/pipeline.json'
_UI_VIDEOSOURCE_TYPE = 'videosource'
_UI_EVENTSTORE_TYPE = 'eventstore'


_UI_VIDEOSOURCE_RTSP_TYPE = 'rtsp-camera'
_UI_VIDEOSOURCE_MV_TYPE = 'mv-camera'

_UI_TERMINAL_TYPE = 'terminal'

with open(_PIPELINE_SET_FILEPATH, 'r') as json_file:
    pipeline_jnode_set = ujson.load(json_file)

migrate_list = map(lambda x: (x['id'], x['type']), pipeline_jnode_set)

# edit pipeline jnode-set
videosource_modules_exist = False
eventstore_module_exist = False
for pipeline_jnode in pipeline_jnode_set:
    for module_jnode in pipeline_jnode['modules']:

        if module_jnode['type'] == _UI_VIDEOSOURCE_TYPE:
            videosource_modules_exist = True

            if pipeline_jnode['type'] == ph.PTYPE_LPR_RTSP:
                module_jnode['type'] = _UI_VIDEOSOURCE_RTSP_TYPE
                module_jnode['title'] = "pipeline.{}".format(_UI_VIDEOSOURCE_RTSP_TYPE)
            elif pipeline_jnode['type'] in [ph.PTYPE_LPR_MV, ph.PTYPE_SPEED]:
                module_jnode['type'] = _UI_VIDEOSOURCE_MV_TYPE
                module_jnode['title'] = "pipeline.{}".format(_UI_VIDEOSOURCE_MV_TYPE)

        elif module_jnode['type'] == _UI_EVENTSTORE_TYPE:
            module_jnode['type'] = _UI_TERMINAL_TYPE
            module_jnode['title'] = "pipeline.{}".format(_UI_TERMINAL_TYPE)
            eventstore_module_exist = True


# if no videosource modules - nothing to change
if True not in [videosource_modules_exist, eventstore_module_exist]:
    exit(0)

fs.write_json_file(pipeline_jnode_set, _PIPELINE_SET_FILEPATH, pretty=True)

# migrate eventstore -> terminal
for pipeline_id, pipeline_type in migrate_list:
    ui_eventstore_jnode_filepath = ph.get_ui_pipeline_jnode_filepath(pipeline_id, _UI_EVENTSTORE_TYPE, '0')
    if not os.path.isfile(ui_eventstore_jnode_filepath):
        continue

    ui_eventstore_jnode = fs.load_json(ui_eventstore_jnode_filepath)
    ui_terminal_jnode_filepath = ph.get_ui_pipeline_jnode_filepath(pipeline_id, _UI_TERMINAL_TYPE, '0')
    if os.path.isfile(ui_terminal_jnode_filepath):
        continue

    # create jnode from default
    terminal_identity = ph.UiIdentity(pipeline_type, _UI_TERMINAL_TYPE, '0')
    ui_terminal_defjnode_filepath = ph.get_ui_def_jnode_filepath(terminal_identity)
    fs.create_jnode_from_default(ui_terminal_defjnode_filepath, ui_terminal_jnode_filepath)

    # link new schema
    terminal_schemapath = ph.get_ui_pipeline_schema_filepath(pipeline_id, _UI_TERMINAL_TYPE, '0')
    fs.ln_schema(terminal_schemapath, ui_terminal_jnode_filepath)

    # edit terminal jnode
    ui_terminal_jnode = fs.load_json(ui_terminal_jnode_filepath)
    schema_path = ui_terminal_jnode['ro']['schema-abspath']
    ui_terminal_jnode = ui_eventstore_jnode
    ui_terminal_jnode['ro']['schema-abspath'] = schema_path

    # rewrite terminal jnode
    fs.write_json_file(ui_terminal_jnode, ui_terminal_jnode_filepath, pretty=True)

    # delete eventstore jnode with dir
    eventstore_identity = ph.UiIdentity(pipeline_type, _UI_EVENTSTORE_TYPE, '0')
    ui_eventstore_dirpath = ph.get_ui_pipeline_jnode_dirpath(pipeline_id, eventstore_identity)
    fs.silent_rm_r(ui_eventstore_dirpath)

# migrate videosource -> rtsp-camera / mv-camera
for pipeline_id, pipeline_type in migrate_list:
    ui_videosource_jnode_filepath = ph.get_ui_pipeline_jnode_filepath(pipeline_id, _UI_VIDEOSOURCE_TYPE, '0')
    if not os.path.isfile(ui_videosource_jnode_filepath):
        continue

    ui_videosource_jnode = fs.load_json(ui_videosource_jnode_filepath)

    if pipeline_type == ph.PTYPE_LPR_RTSP:
        ui_rtsp_camera_jnode_filepath = ph.get_ui_pipeline_jnode_filepath(pipeline_id, _UI_VIDEOSOURCE_RTSP_TYPE, '0')
        if os.path.isfile(ui_rtsp_camera_jnode_filepath):
            continue

        # create jnode from default
        rtsp_camera_identity = ph.UiIdentity(pipeline_type, _UI_VIDEOSOURCE_RTSP_TYPE, '0')
        ui_rtsp_camera_defjnode_filepath = ph.get_ui_def_jnode_filepath(rtsp_camera_identity)
        fs.create_jnode_from_default(ui_rtsp_camera_defjnode_filepath, ui_rtsp_camera_jnode_filepath)

        # link new schema
        rtsp_camera_schemapath = ph.get_ui_pipeline_schema_filepath(pipeline_id, _UI_VIDEOSOURCE_RTSP_TYPE, '0')
        fs.ln_schema(rtsp_camera_schemapath, ui_rtsp_camera_jnode_filepath)

        # edit rtsp-camera jnode
        ui_rtsp_camera_jnode = fs.load_json(ui_rtsp_camera_jnode_filepath)

        # migrate config
        ui_rtsp_camera_jnode['ro']['rgbs'] = ui_videosource_jnode['ro'].get('rgbs', False)
        ui_rtsp_camera_jnode['ro']['mcgst-scene'] = ui_videosource_jnode['ro'].get('mcgst-scene', True)

        conf_jnode = ui_rtsp_camera_jnode['rw']['conf']
        video_jnode = conf_jnode['video']

        conf_jnode['url'] = ui_videosource_jnode['rw']['streaming'].get('url', '')

        video_jnode['format'] = 'video/H264' if ui_videosource_jnode['rw']['videostream']['codec'] == 'h264' \
            else 'video/JPEG'

        video_jnode['skip-rate'] = ui_videosource_jnode['rw']['videostream']['SkipRate']
        video_jnode['decoder'] = 'hw/auto' if ui_videosource_jnode['rw']['videostream']['hw-decode'] else 'sw/auto'
        video_jnode['grayscale'] = ui_videosource_jnode['rw']['videostream'].get('color-mode') == 'grayscale'

        if ui_videosource_jnode['rw']['streaming']['transport'] == 'rtp-over-tcp':
            video_jnode['transport'] = ['RTP/AVP/TCP']
        else:
            video_jnode['transport'] = ['RTP/AVP/UDP', 'RTP/AVP/TCP']

        # rewrite rtsp-camera jnode
        fs.write_json_file(ui_rtsp_camera_jnode, ui_rtsp_camera_jnode_filepath, pretty=True)

    elif pipeline_type in [ph.PTYPE_SPEED, ph.PTYPE_LPR_MV]:
        ui_mv_camera_jnode_filepath = ph.get_ui_pipeline_jnode_filepath(pipeline_id, _UI_VIDEOSOURCE_MV_TYPE, '0')
        if os.path.isfile(ui_mv_camera_jnode_filepath):
            continue

        # create jnode from default
        mv_camera_identity = ph.UiIdentity(pipeline_type, _UI_VIDEOSOURCE_MV_TYPE, '0')
        ui_mv_camera_defjnode_filepath = ph.get_ui_def_jnode_filepath(mv_camera_identity, ujson.dumps(ui_videosource_jnode['rw']))
        fs.create_jnode_from_default(ui_mv_camera_defjnode_filepath, ui_mv_camera_jnode_filepath)

        # link new schema
        rtsp_camera_schemapath = ph.get_ui_pipeline_schema_filepath(pipeline_id, _UI_VIDEOSOURCE_RTSP_TYPE, '0')
        fs.ln_schema(rtsp_camera_schemapath, ui_mv_camera_jnode_filepath)

        # edit mv-camera jnode
        # TODO:mirgate mv-cameras after changing ui-jnode

        ui_mv_camera_jnode = fs.load_json(ui_mv_camera_jnode_filepath)
        schema_path = ui_mv_camera_jnode['ro']['schema-abspath']
        ui_mv_camera_jnode = ui_videosource_jnode
        ui_mv_camera_jnode['ro']['schema-abspath'] = schema_path

        # rewrite mv-camera jnode
        fs.write_json_file(ui_mv_camera_jnode, ui_mv_camera_jnode_filepath, pretty=True)

    # delete videosource jnode with dir
    videosource_identity = ph.UiIdentity(pipeline_type, _UI_VIDEOSOURCE_TYPE, '0')
    ui_videosource_dirpath = ph.get_ui_pipeline_jnode_dirpath(pipeline_id, videosource_identity)
    fs.silent_rm_r(ui_videosource_dirpath)

