import csv
from django.core import management
from django.core.management import BaseCommand


class Command(BaseCommand):
    """
    usage: `python manage.py translate_from_csv --file file [...]`
    """

    def add_arguments(self, parser):
        parser.add_argument("--file", type=str)
        parser.add_argument(
            "--model", type=str, choices=["instrument", "module"], default="instrument"
        )

    def handle(self, *args, **options):
        filename = options["file"]
        model = options["model"]
        # self.stdout.write(filename)
        with open(filename) as f:
            reader = csv.reader(f)
            for original, english, french in reader:
                # self.stdout.write(f"{original}\t\t\t{english}\t\t\t{french}")
                try:
                    management.call_command(
                        "migrate_page_translation",
                        slug=english.strip(),
                        original=original.strip(),
                        language="en",
                        model=model,
                    )
                except Exception as e:
                    self.stderr.write(e.__str__())

                try:
                    management.call_command(
                        "migrate_page_translation",
                        slug=french.strip(),
                        original=original.strip(),
                        language="fr",
                        model=model,
                    )
                except Exception as e:
                    self.stderr.write(e.__str__())
