#!/usr/bin/python

import semver
from edge.com import fs
from edge.webserver.sysconf import ph

_TARGET_VER = '0.37.33'
_OLD_TO_NEW_TEMPLATE_MAP = fs.load_json3('/opt/edge/share/lpr/plate-map.json')


def _change_templates(unit_info):
    """
    :type unit_info: dict
    :rtype: None
    """
    ui_ref = unit_info['ref']
    ui_mod = ph.UiMod.create(ui_ref)
    ui_conf = ui_mod.load_conf()

    source_ver = ui_conf['ro'].get('ver')
    if source_ver is not None:
        if semver.compare(source_ver, _TARGET_VER) >= 0:
            return

    ui_conf2 = ui_conf['rw']['plate-recognizer']

    new_templates = []
    old_templates = ui_conf2.get('templates') or list()
    for old_template in old_templates:
        # "804-0-1" -> "ua.1" || "ua.1" --> "ua.1"
        new_template = _OLD_TO_NEW_TEMPLATE_MAP.get(old_template, old_template)
        new_templates.append(new_template)

    ui_conf2['templates'] = new_templates
    ui_conf['ro']['ver'] = _TARGET_VER
    ui_mod.save_conf(ui_conf)


def _main():
    root_info = ph.RootInfoUiconf.get_info()
    ph.RootInfoUiconf.map_units_r(root_info, map_fn=_change_templates,  unit_types=[ph.UI_TYPE_LPR])


if __name__ == '__main__':
    _main()
