# -*- coding: utf-8 -*-

#  Copyright © 2013-2017  B. Clausius <barcc@gmx.de>
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sys, os
from glob import glob
from contextlib import suppress


def update_linguas():
    import polib
    min_percent_translated = 20
    cnt_skipped = 0
    with open('po/LINGUAS', 'wt', encoding='utf-8') as linguas:
        po_files = sorted(glob('po/*.po'))
        for po_file in po_files:
            percent_translated = polib.pofile(po_file).percent_translated()
            if percent_translated < min_percent_translated:
                print('skipping po file {!r} ({}%<{}% translated)'.format(
                            po_file, percent_translated, min_percent_translated),
                    file=sys.stderr)
                cnt_skipped += 1
            else:
                print(os.path.splitext(os.path.basename(po_file))[0], file=linguas)
        print('skipped {}/{} po files'.format(cnt_skipped, len(po_files)), file=sys.stderr)
                
def get_linguas():
    with open('po/LINGUAS', 'rt', encoding='utf-8') as linguas:
        return linguas.read().splitlines()
        
def generate_lang_translations():
    from pybiklib.dialogs import get_langname_from_code_func
    langname_from_code = get_langname_from_code_func()
    names = ((code, langname_from_code(code)) for code in get_linguas())
    names = {code: name for code, name in names if name is not None}
    print(names)
    
def generate_all_lang_translations(file=sys.stdout):
    import icu  # to be sure get_langname_from_code_func does not return a fallback function
    from subprocess import Popen, PIPE
    from ast import literal_eval
    from pprint import pformat
    
    processes = []
    env = os.environ.copy()
    for lang in get_linguas():
        env['LC_MESSAGES'] = lang+'.UTF-8'
        script = 'import buildlib.utils as m; m.generate_lang_translations()'
        print(lang, end=' ', flush=True)
        processes.append((lang, Popen(['python3', '-c', script], env=env, stdout=PIPE)))
    print()
    
    langs = {}
    for lang, process in processes:
        print(lang, end=' ', flush=True)
        outstr, unused_err = process.communicate()
        outstr = outstr.strip().decode('utf-8')
        try:
            langs[lang] = literal_eval(outstr)
        except SyntaxError:
            print('code for lang %r:' % lang, repr(outstr))
            raise
    print()
    
    print('# -*- coding: utf-8 -*-', file=file)
    print('# generated file\n', file=file)
    print('languages = (', file=file)
    print(pformat(langs), file=file)
    print(')\n', file=file)
    
def modify_file(filename, subs, count=1):
    from shutil import copymode
    import re
    print('modifying', filename)
    with open(filename, 'rt', encoding='utf-8') as f:
        rtext = f.read()
    wtext = rtext
    for pattern, repl in subs:
        wtext = re.sub(pattern, repl, wtext, count=count, flags=re.MULTILINE)
    if wtext == rtext:
        return False
    tmpfilename = filename+'.tmp'
    with open(tmpfilename, 'xt', encoding='utf-8') as f:
        f.write(wtext)
    copymode(filename, tmpfilename)
    os.rename(tmpfilename, filename)
    return True
        
variants = (
    {'id': 'qtw',  'name': 'QtWidgets (default)',  'group': 'qtvariant',  'type': 'enum'},
    {'id': 'qtq',  'name': 'QtQuick/QML',          'group': 'qtvariant',  'type': 'enum'},
    {'id': 'ogl',  'name': 'OpenGL (default)',     'group': 'glvariant',  'type': 'enum'},
    {'id': 'es2',  'name': 'OpenGLES2',            'group': 'glvariant',  'type': 'enum'},
    {'id': 'd',    'name': 'debug OpenGL/ES',      'group': 'gldebug',    'type': 'bool'},
    {'id': 'os',   'name': 'offscreen',            'group': 'offscreen',  'type': 'bool'},
    {'id': 'all',  'name': 'all variants',                                'type': None},
)

def accepted_variants():
    return {v['id']: v for v in variants}
    
def variant_string():
    return ', '.join('%s (%s)'%(v['id'],v['name']) for v in variants)
    
def group_variants(variant_ids):
    grouped_variants = {}
    for v in variants:
        if v['type'] == None:
            continue
        values, all_values = grouped_variants.setdefault(v['group'], [[], []])
        if v['type'] == 'bool':
            values.append(None)
            all_values.append(None)
        if v['id'] in variant_ids or 'all' in variant_ids:
            values.append(v['id'])
        all_values.append(v['id'])
    # set default enum variants
    for v in variants:
        if v['type'] != 'enum':
            continue
        values, all_values = grouped_variants[v['group']]
        if not values:
            values.append(v['id'])
    for v in variants:
        with suppress(KeyError):
            g = v['group']
            values, all_values = grouped_variants.pop(g)
            yield g, values, all_values
    

