#!/usr/bin/python

from edge.com import fs
from edge.webserver.sysconf import ph
from edge.webserver.sysconf.dgconf.setupstore import SsDgconf
from edge.webserver.sysconf.uiconf.pipeline import PipelineUiconf


def migrate_setupstore_conf(old_new_uimod_list):
    """
    :type old_new_uimod_list: list[(ph.UiMod, ph.UiMod)]
    """
    # def reduce_fn(acc, old_new_uimod):
    #     """
    #     :type acc: dict
    #     :type old_new_uimod: (ph.UiMod, old_new_uimod)
    #     :rtype: dict
    #     """
    #     old_uimod, new_uimod = old_new_uimod
    #     acc[old_uimod.conf_path] = new_uimod.conf_path
    #
    # old_to_new_dgconf_dir_map = reduce(reduce_fn, old_new_uimod_list, dict())

    term_pids = map(lambda (x, y): x.pid, old_new_uimod_list)

    # edit setupstore/main.conf
    dgconf = SsDgconf.load_conf()

    dgconf_groups = dgconf['groups']
    for group_info in dgconf_groups:
        group_name = group_info['name']
        if 'pipeline' not in group_name:
            continue

        term_pid = group_name.split('-')[-1]
        if term_pid not in term_pids:
            continue

        modules_info = group_info['modules']
        modules_info = filter(lambda x: 'rtspserver' not in x, modules_info)
        rtsp_server_basedir = '/etc/edge/rtspserver.{}'.format(int(term_pid) * 10 + 1)
        modules_info.append(rtsp_server_basedir)
        group_info['modules'] = modules_info

    SsDgconf.save_conf(dgconf)


def _main():
    if not fs.path_exists(PipelineUiconf.CONF_PATH):
        return

    terms_info = PipelineUiconf.load_conf()

    old_new_uimod_list = []
    for term_info in terms_info:
        term_pid = term_info['id']
        if term_info['type'] == PipelineUiconf.PTYPE_TERM_RTSP:
            continue

        modules_info = term_info['modules']
        for module_info in modules_info:
            uimod_type = module_info['type']
            if uimod_type != ph.UI_TYPE_RTSP_STREAMING:
                continue

            old_uimod_id = module_info['id']
            new_uimod_id = str(int(old_uimod_id) + 1)

            module_info['id'] = new_uimod_id

            old_uimod = ph.UiMod(term_pid, uimod_type, old_uimod_id)
            new_uimod = ph.UiMod(term_pid, uimod_type, new_uimod_id)
            old_new_uimod_list.append((old_uimod, new_uimod))

    if len(old_new_uimod_list) == 0:
        return

    for old_uimod, new_uimod in old_new_uimod_list:
        fs.move_files(old_uimod.conf_path, new_uimod.conf_path)
        fs.move_files(old_uimod.schema_path, new_uimod.schema_path)

    # TODO: move/delete /etc/edge/rtspserver.x dir ?
    # write to fs
    PipelineUiconf.save_conf(terms_info)
    migrate_setupstore_conf(old_new_uimod_list)


if __name__ == '__main__':
    _main()
