#!/usr/bin/python3

# Copyright © 2012, 2013 Jakub Wilk <jwilk@jwilk.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import os
import re
import sys
import urllib.request

basedir = os.path.join(
    os.path.dirname(__file__),
    os.pardir,
)
sys.path[:0] = [basedir]

from lib import ling

def main():
    url = 'https://raw.github.com/vslavik/poedit/master/src/isocodes.cpp'
    regexp = re.compile(r'^\s*\{\s*_T\("([a-z]{2,}(?:_[A-Z]{2})?(?:@[a-z]+)?)"\)\s*,\s*_T\("([^"]+)"\)\s*\}\s*,?\s*$')
    n_okay = 0
    with urllib.request.urlopen(url) as file:
        for line in file:
            line = line.decode('ASCII').rstrip()
            match = regexp.match(line)
            if match is None:
                continue
            poedit_ll, name = match.groups()
            poedit_ll = ling.parse_language(poedit_ll)
            try:
                gi_ll = ling.get_language_for_name(name)
            except LookupError:
                gi_ll = None
            if gi_ll != poedit_ll:
                print('[{}]'.format(poedit_ll))
                try:
                    if poedit_ll.fix_codes():
                        raise ling.LanguageError
                except ling.LanguageError:
                    if gi_ll is None:
                        print('# Unknown language code')
                    else:
                        print('# Unknown language code; should be: {}'.format(gi_ll))
                else:
                    if gi_ll is not None:
                        print('# Not {}'.format(gi_ll))
                print('names =', name)
                print()
            else:
                n_okay += 1
    print('# No changes required for {} languages'.format(n_okay))

if __name__ == '__main__':
    main()

# vim:ts=4 sw=4 et
