#! /usr/bin/env python
"""
Post update hook script to update message IDs in the resx file.

- Removes messages no longer present in template
- Adds new units not present in template
- Resets translation if string has been changed in template
"""

from __future__ import print_function

import glob
import os
import subprocess
import sys

from translate.storage.resx import RESXFile


def build_index(storage):
    index = {}

    for unit in storage.units:
        index[unit.getid()] = unit

    return index


def find_changes(index, storage):
    """Finds changed units in storage"""
    result = set()

    for unit in storage.units:
        unitid = unit.getid()
        if unitid not in index:
            continue
        if unit.target != index[unitid].target:
            result.add(unitid)

    return result


def update_file(template, index, changes, filename):
    storage = RESXFile.parsefile(filename)
    sindex = build_index(storage)
    changed = False

    # Add missing units
    for unit in template.units:
        if unit.getid() not in sindex:
            storage.addunit(unit, True)
            changed = True

    # Remove extra units and apply target changes
    for unit in storage.units:
        unitid = unit.getid()
        if unitid not in index:
            storage.body.remove(unit.xmlelement)
            changed = True
        if unitid in changes:
            unit.target = index[unitid].target
            changed = True

    if changed:
        storage.save()


def main():
    if os.environ.get('WL_FILE_FORMAT') != 'resx':
        print('Invalid file format!')
        sys.exit(1)

    if not os.environ.get('WL_TEMPLATE'):
        print('Missing template!')
        sys.exit(1)

    if not os.environ.get('WL_FILEMASK'):
        print('Missing filemask!')
        sys.exit(1)

    if not os.environ.get('WL_PATH'):
        print('Missing path!')
        sys.exit(1)

    if not os.environ.get('WL_PREVIOUS_HEAD'):
        print('Missing previous HEAD!')
        sys.exit(1)

    os.chdir(os.environ.get('WL_PATH'))

    templatename = os.environ.get('WL_TEMPLATE')

    template = RESXFile.parsefile(templatename)
    index = build_index(template)

    oldtemplate = subprocess.check_output([
        'git', 'show', '{0}:{1}'.format(
            os.environ.get('WL_PREVIOUS_HEAD'),
            templatename
        )
    ])

    old = RESXFile.parsestring(oldtemplate)

    changes = find_changes(index, old)

    for filename in glob.glob(os.environ.get('WL_FILEMASK')):
        if filename != templatename:
            update_file(template, index, changes, filename)

    if subprocess.call(['git', 'commit', '--dry-run', '-a']) == 0:
        ret = subprocess.call(
            ['git', 'commit', '-a', '-m', 'Updated translation files']
        )
        if ret == 0:
            ret = subprocess.call(['git', 'push'])
        sys.exit(ret)


if __name__ == '__main__':
    main()
