#!/usr/bin/python

from edge.webserver.sysconf import ph
from edge.webserver.sysconf.uiconf.pipeline import PipelineUiconf

_UI_TYPE_GEOLOCATION = 'geolocation'


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

    if gnss_provider_conf['provider'] == 'manual':
        rt_conf = {
            'azimuth': az,
            'source': ['static', gnss_provider_conf['latitude'], gnss_provider_conf['longitude']]
        }
    elif gnss_provider_conf['provider'] == 'controller':
        rt_conf = {
            'azimuth': az,
            'source': ['gpsd', 'localhost', 2947]
        }

    else:
        rt_conf = dict()

    return rt_conf


def _main():
    terms_info = PipelineUiconf.load_conf()

    geolocation_modules_exist = False
    for term_info in terms_info:
        for module_info in term_info['modules']:
            if module_info['type'] == _UI_TYPE_GEOLOCATION:
                module_info['type'] = ph.UI_TYPE_GNSS
                module_info['title'] = 'pipeline.{}'.format(ph.UI_TYPE_GNSS)
                geolocation_modules_exist = True

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

    PipelineUiconf.save_conf(terms_info)

    for term_info in terms_info:
        term_pid = term_info['id']
        geolocation_uimod = ph.UiMod(term_pid, _UI_TYPE_GEOLOCATION, '0')
        geolocation_uiconf = geolocation_uimod.load_conf(default=None)
        if geolocation_uiconf is None:
            continue

        gnss_uimod = ph.UiMod(term_pid, ph.UI_TYPE_GNSS, '0')
        if gnss_uimod.load_conf(default=None) is None:
            continue

        gnss_uimod.install()
        gnss_uiconf = gnss_uimod.load_conf()
        gnss_pub = gnss_uiconf['rw']  # type: dict
        gnss_provirer = gnss_pub['conf']['providers'][0]

        geolocation_pub = geolocation_uiconf['rw']
        geolocation_mode = geolocation_pub.get('mode')

        if geolocation_mode == 'manual':
            lat = geolocation_pub.get('latitude', 0)
            log = geolocation_pub.get('longitude', 0)
            gnss_provirer['latitude'] = lat
            gnss_provirer['longitude'] = log

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

        # add rt conf for sc and or
        gnss_uiconf['rt'] = _geodata_rt_conf(gnss_pub['conf'])

        # rewrite gnss jnode
        gnss_uimod.save_conf(gnss_uiconf)
        geolocation_uimod.uninstall()


if __name__ == '__main__':
    _main()
