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

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


def _geodata_rt_conf(new_jnode):
    """
    :type new_jnode: dict
    :rtype: dict
    """
    az = new_jnode.get('azimuth', None)
    provider_jnode = new_jnode['providers'][0]

    if provider_jnode['provider'] == 'manual':
        jnode = {
            "azimuth": az,
            "source": ["static", provider_jnode['latitude'], provider_jnode['longitude']]
        }
    elif provider_jnode['provider'] == 'controller':
        jnode = {
            "azimuth": az,
            "source": ["gpsd", "localhost", 2947]
        }
    else:
        jnode = dict()

    return jnode


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

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
geolocation_modules_exist = False
for pipeline_jnode in pipeline_jnode_set:
    for module_jnode in pipeline_jnode['modules']:
        if module_jnode['type'] == _UI_GEOLOCATION_TYPE:
            geolocation_modules_exist = True
            module_jnode['type'] = ph.UI_TYPE_GNSS
            module_jnode['title'] = "pipeline.{}".format(ph.UI_TYPE_GNSS)


# if no geolocation modules - nothing to change
if not geolocation_modules_exist:
    exit(0)

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

for pipeline_id, pipeline_type in migrate_list:
    ui_geolocation_jnode_filepath = ph.get_ui_pipeline_jnode_filepath(pipeline_id, _UI_GEOLOCATION_TYPE, '0')
    ui_geolocation_jnode = fs.load_json(ui_geolocation_jnode_filepath)
    if ui_geolocation_jnode is None:
        continue

    ui_gnss_jnode_filepath = ph.get_ui_pipeline_jnode_filepath(pipeline_id, ph.UI_TYPE_GNSS, '0')
    if os.path.isfile(ui_gnss_jnode_filepath):
        continue

    # create jnode from default
    gnss_identity = ph.UiIdentity(pipeline_type, ph.UI_TYPE_GNSS, '0')
    ui_gnss_defjnode_filepath = ph.get_ui_def_jnode_filepath(gnss_identity)
    fs.create_jnode_from_default(ui_gnss_defjnode_filepath, ui_gnss_jnode_filepath)

    # link new gnss schema
    gnss_schemapath = ph.get_ui_pipeline_schema_filepath(pipeline_id, ph.UI_TYPE_GNSS, '0')
    fs.ln_schema(gnss_schemapath, ui_gnss_jnode_filepath)

    # edit gnss jnode
    ui_gnss_jnode = fs.load_json(ui_gnss_jnode_filepath)

    provirer_jnode = ui_gnss_jnode['rw']['conf']['providers'][0]

    geolocation_mode = ui_geolocation_jnode['rw'].get('mode')
    lat = log = None
    if geolocation_mode == 'manual':
        lat = ui_geolocation_jnode['rw'].get('latitude', 0)
        log = ui_geolocation_jnode['rw'].get('longitude', 0)
        provirer_jnode['latitude'] = lat
        provirer_jnode['longitude'] = log

    elif geolocation_mode == 'auto':
        provirer_jnode['provider'] = 'controller'

    # add rt conf for sc and or
    ui_gnss_jnode['rt'] = _geodata_rt_conf(ui_gnss_jnode['rw']['conf'])

    # rewrite gnss jnode
    fs.write_json_file(ui_gnss_jnode, ui_gnss_jnode_filepath, pretty=True)

    # delete geolocation jnode with dir
    geolocation_identity = ph.UiIdentity(pipeline_type, _UI_GEOLOCATION_TYPE, '0')
    ui_geolocation_dirpath = ph.get_ui_pipeline_jnode_dirpath(pipeline_id, geolocation_identity)
    fs.silent_rm_r(ui_geolocation_dirpath)

