import argparse
import json
import sys

from django.apps import apps
from django.core.management.base import BaseCommand, CommandError
from django.utils.module_loading import import_string

from ...strategies import QuerySetStrategy


class Command(BaseCommand):
    help = "Dump the data generated by a given strategy."

    def add_arguments(self, parser):
        parser.add_argument(
            "model_label",
            metavar="app_label[.ModelName]",
            help="Restricts dumped data to the specified app_label or app_label.ModelName.",
        )
        parser.add_argument(
            "strategy_class",
            metavar="foo.bar.MyStrategy",
            help="Export strategy class.",
        )
        parser.add_argument(
            "database",
            help="The database name to sync.",
        )
        parser.add_argument(
            "kwargs",
            nargs="?",
            type=argparse.FileType("r"),
            default=sys.stdin,
            help="Path to file containing JSON encoded kwargs for the strategy",
        )

    def handle(self, model_label, strategy_class, kwargs, database, **options):
        app_name, model_name = model_label.split(".")
        app_config = apps.get_app_config(app_name)
        model = app_config.get_model(model_name)

        strategy_kwargs = json.load(kwargs)
        strategy = import_string(strategy_class)(**strategy_kwargs)

        if not isinstance(strategy, QuerySetStrategy):
            raise CommandError("Strategy not locally exportable")

        strategy.export_local(database, model, self.stdout)
