#!/usr/bin/python

from edge.path_helpers import *
from edge.com.fs import ln_schema, silent_mkdir_r
import shutil
import os
import ujson

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


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

pipelines = filter(lambda x: x['type'] == PTYPE_SPEED, pipeline_jnode_set)
speed_ids = map(lambda x: x['id'], pipelines)

pipelines = filter(lambda x: x['type'] == PTYPE_LPR_RTSP or x['type'] == PTYPE_LPR_MV, pipeline_jnode_set)
lpr_ids = map(lambda x: x['id'], pipelines)

# append fact-rules to all pipelines
fact_rules_jnode = {
    "title": "pipeline.fact-rules",
    "type": "fact-rules",
    "datasource": False,
    "id": "0"
}

# add fact-rules to all pipelines
for pipeline_jnode in pipeline_jnode_set:
    already_exist = False
    for module_jnode in pipeline_jnode['modules']:
        if module_jnode == fact_rules_jnode:
            already_exist = True

    if not already_exist:
        pipeline_jnode['modules'].append(fact_rules_jnode)

# write new pipeline.json to disk
with open(_PIPELINE_SET_FILEPATH, 'w') as json_file:
    ujson.dump(pipeline_jnode_set, json_file, indent=2)

for speed_id in speed_ids:
    # cp def jnode from default path
    jnode_file_path = get_ui_pipeline_jnode_filepath(speed_id, UI_TYPE_TRANSIT, '0')
    ui_identity = UiIdentity(PTYPE_SPEED, UI_TYPE_TRANSIT, '0')
    silent_mkdir_r(os.path.dirname(jnode_file_path))

    def_jnode_file_path = get_ui_def_jnode_filepath(ui_identity, None)
    shutil.copy2(def_jnode_file_path, jnode_file_path)

    ui_schema_filepath = get_ui_pipeline_schema_filepath(speed_id, ui_identity.type, ui_identity.id)
    ln_schema(ui_schema_filepath, jnode_file_path)


for lpr_id in lpr_ids:
    # cp def jnode from default path
    jnode_file_path = get_ui_pipeline_jnode_filepath(lpr_id, UI_TYPE_TRANSIT, '0')
    ui_identity = UiIdentity(PTYPE_LPR_RTSP, UI_TYPE_TRANSIT, '0')
    silent_mkdir_r(os.path.dirname(jnode_file_path))

    def_jnode_file_path = get_ui_def_jnode_filepath(ui_identity, None)
    shutil.copy2(def_jnode_file_path, jnode_file_path)

    ui_schema_filepath = get_ui_pipeline_schema_filepath(lpr_id, ui_identity.type, ui_identity.id)
    ln_schema(ui_schema_filepath, jnode_file_path)
