import csv
import os
import polib

from django.core.management.base import BaseCommand, CommandError
from django.conf import settings


class Command(BaseCommand):
    help = "Makemessages with ios translation json."

    def add_arguments(self, parser):
        parser.add_argument('language_code')

    def handle(self, *args, **options):
        locale_path = settings.LOCALE_PATHS[0]
        client_path = options['language_code'] + '/LC_MESSAGES/client.po'
        file_path = os.path.join(locale_path, client_path)

        if os.path.exists(file_path):
            po_file = polib.pofile(file_path)
        else:
            po_file = polib.POFile()
            po_file.metadata = {
                'Project-Id-Version': '1.0',
                'Report-Msgid-Bugs-To': 'you@example.com',
                'POT-Creation-Date': '2007-10-18 14:00+0100',
                'PO-Revision-Date': '2007-10-18 14:00+0100',
                'Last-Translator': 'you <you@example.com>',
                'Language-Team': 'English <yourteam@example.com>',
                'MIME-Version': '1.0',
                'Content-Type': 'text/plain; charset=utf-8',
                'Content-Transfer-Encoding': '8bit',
            }

        csv_path = os.path.join(locale_path, 'ios-client.csv')
        reader_csv = csv.reader(open(csv_path))

        msgid_already_translated = [entry.msgid for entry in po_file.translated_entries()]

        for row in reader_csv:
            if row and row[0] and row[0] not in msgid_already_translated:
                if options['language_code'] == 'fr':
                    msgstr = row[3]
                elif options['language_code'] == 'en':
                    if row[2]:
                        msgstr = row[2]
                    else:
                        raise CommandError(
                            "No english reference is provided at line %s." % reader_csv.line_num
                        )
                else:
                    msgstr = ''

                entry = polib.POEntry(
                    msgid=u'%s' % row[0],
                    msgstr=u'%s' % msgstr,
                    msgctxt=u'%s' % row[1]
                )
                if entry not in po_file:
                    po_file.append(entry)

        try:
            po_file.save(file_path)
        except FileNotFoundError:
            raise CommandError("You must run `makemessages` command before `makemessagesios`.")
