#!/usr/bin/python

from edge.path_helpers import *
import ujson

_PIPELINE_SET_FILEPATH = '/etc/edge/setupstore/admin/actions/pipeline.json'

_MV_HALTACTION_DFLT =  [
    "0:python /opt/edge/bin/led-ctl.py camera green cont;",
    "1:python /opt/edge/bin/led-ctl.py camera red flash-fast; python /etc/edge/psuctl.d/camera_cold_reboot.py",
    "2:python /opt/edge/bin/led-ctl.py camera red cont"
]

_RG_HALTACTION_DFLT = [
    "0:python /opt/edge/bin/led-ctl.py camera green cont",
    "1:python /opt/edge/bin/led-ctl.py camera red flash-fast",
    "2:python /opt/edge/bin/led-ctl.py camera red cont; kill -9 $PPID"
]

_RA_HALTACTION_DFLT = [
    "0:python /opt/edge/bin/led-ctl.py radar green cont",
    "1:python /opt/edge/bin/led-ctl.py radar red flash-fast; python /etc/edge/psuctl.d/radar_cold_reboot.py",
    "2:python /opt/edge/bin/led-ctl.py radar red cont"
]

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

# mv pipelines
pipelines_to_migrate = filter(lambda x: x['type'] == PTYPE_LPR_MV, pipeline_jnode_set)
migrate_list = map(lambda x: x['id'], pipelines_to_migrate)

for pipeline_id in migrate_list:
    ui_jnode_filepath = get_ui_pipeline_jnode_filepath(pipeline_id, UI_TYPE_VIDEOSOURCE, '0')
    with open(ui_jnode_filepath, 'r') as json_file:
        ui_jnode = ujson.load(json_file)

    if ui_jnode['ro'].get('haltaction') is None:
        ui_jnode['ro']['haltaction'] = _MV_HALTACTION_DFLT

    with open(ui_jnode_filepath, 'w') as json_file:
        ujson.dump(ui_jnode, json_file, indent=2)

# ra pipelines
pipelines_to_migrate = filter(lambda x: x['type'] == PTYPE_SPEED, pipeline_jnode_set)
migrate_list = map(lambda x: x['id'], pipelines_to_migrate)

for pipeline_id in migrate_list:
    ui_jnode_filepath = get_ui_pipeline_jnode_filepath(pipeline_id, UI_TYPE_LOCATION, '0')
    with open(ui_jnode_filepath, 'r') as json_file:
        ui_jnode = ujson.load(json_file)

    if ui_jnode['ro'].get('haltaction') is None:
        ui_jnode['ro']['haltaction'] = _RA_HALTACTION_DFLT

    with open(ui_jnode_filepath, 'w') as json_file:
        ujson.dump(ui_jnode, json_file, indent=2)

# rg pipelines
pipelines_to_migrate = filter(lambda x: x['type'] == PTYPE_LPR_RTSP, pipeline_jnode_set)
migrate_list = map(lambda x: x['id'], pipelines_to_migrate)

for pipeline_id in migrate_list:
    ui_jnode_filepath = get_ui_pipeline_jnode_filepath(pipeline_id, UI_TYPE_VIDEOSOURCE, '0')
    with open(ui_jnode_filepath, 'r') as json_file:
        ui_jnode = ujson.load(json_file)

    if ui_jnode['ro'].get('haltaction') is None:
        ui_jnode['ro']['haltaction'] = _RG_HALTACTION_DFLT

    with open(ui_jnode_filepath, 'w') as json_file:
        ujson.dump(ui_jnode, json_file, indent=2)
