# coding: utf-8

from collections import defaultdict
from optparse import make_option

import django
import polib
from django.core.management.base import BaseCommand
from django_tanker.management.commands import DownloadUploadBaseCommand
from django_tanker.utils import find_translation_files


class Command(DownloadUploadBaseCommand):
    help = u'Uploads *.po files to the Tanker instance'

    if django.VERSION <= (1, 7):
        tanker_option_list = DownloadUploadBaseCommand.tanker_option_list + [
            make_option(
                '--mode',
                '-m',
                action='store',
                type='choice',
                default=None,
                choices=['replace', 'update', 'merge'],
                help=u'Tanker uploading mode',
            )
        ]

        option_list = list(BaseCommand.option_list) + tanker_option_list
    else:

        def add_arguments(self, parser):
            super().add_arguments(parser)
            parser.add_argument(
                '--mode',
                '-m',
                action='store',
                default=None,
                choices=['replace', 'update', 'merge'],
                help=u'Tanker uploading mode',
            ),

    def handle(self, *args, **options):
        self.options = self.configure_options(**options)

        keysets = defaultdict(
            lambda: dict(
                keys=defaultdict(
                    lambda: dict(
                        info=dict(),
                        translations=defaultdict(lambda: dict(author='mkznts')),
                    )
                )
            )
        )

        files = find_translation_files(
            self.options['language'], self.options['basepath']
        )

        for app, (lang, path) in files:
            if app is not None:
                continue

            pofile = polib.pofile(path)

            for entry in pofile:

                if '::' not in entry.msgid:
                    print(entry.msgid)
                    continue

                print(entry.msgid)
                ks, key = entry.msgid.split('::')

                keysets[ks]['keys'][key]['translations'][lang][
                    'form'
                ] = entry.msgstr

        data = {
            "export_info": {},
            "keysets": keysets,
            "meta": {"languages": list(self.options['language'])},
        }

        from procu.api.utils import json_dumps

        file_info = {'filename': 'backend', 'data': json_dumps(data)}

        self.tanker.upload(
            keyset='test',
            language=','.join(list(self.options['language'])),
            file_info=file_info,
            file_format='tjson',
            mode='create',
            branch=self.options['branch'],
            key_not_language=self.options['key_not_language'],
        )
