package commands;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.mongodb.MongoClient;
import core.ApplicationConfiguration;
import core.TaskType;
import helpers.TextTaskConfig;
import helpers.WebTaskConfig;
import io.dropwizard.cli.ConfiguredCommand;
import io.dropwizard.setup.Bootstrap;
import modules.ApplicationModule;
import net.sourceforge.argparse4j.inf.Namespace;
import objects.Flag;
import objects.tasks.Task;
import objects.tasks.TaskCryptoContent;
import objects.tasks.TaskWebContent;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Morphia;
import repositories.TasksRepository;

import java.util.List;
import java.util.stream.Collectors;

public class RegisterTasksCommand extends ConfiguredCommand<ApplicationConfiguration>
{
    private static final String COMMAND_NAME = "registertasks";
    private static final String COMMAND_DESCRIPTION = "Register tasks";

    public RegisterTasksCommand()
    {
        super(COMMAND_NAME, COMMAND_DESCRIPTION);
    }

    private void initializeTasks(ApplicationConfiguration applicationConfiguration, Injector injector)
    {
        Datastore datastore = injector.getInstance(Datastore.class);
        TasksRepository tasksRepository = injector.getInstance(TasksRepository.class);

        List<TextTaskConfig> cryptoTasks = applicationConfiguration.getTextTasks();
        List<WebTaskConfig> webTasks = applicationConfiguration.getWebTasks();

        datastore.getCollection(Task.class).drop();

        cryptoTasks.forEach(cryptoTaskConfig -> {

            cryptoTaskConfig.getFlags().stream()
                    .map(Flag::new)
                    .collect(Collectors.toList());

            tasksRepository.add(new Task(
                    cryptoTaskConfig.getName(),
                    cryptoTaskConfig.getLevel(),
                    TaskType.TEXT,
                    cryptoTaskConfig.getFlags().stream()
                            .map(Flag::new)
                            .collect(Collectors.toList()),
                    new TaskCryptoContent(cryptoTaskConfig.getText())
            ));
        });

        webTasks.forEach(webTaskConfig -> tasksRepository.add(new Task(
                webTaskConfig.getName(),
                webTaskConfig.getLevel(),
                TaskType.WEB,
                webTaskConfig.getFlags().stream()
                        .map(Flag::new)
                        .collect(Collectors.toList()),
                new TaskWebContent(webTaskConfig.getUrl())
        )));
    }

    @Override
    protected void run(Bootstrap<ApplicationConfiguration> bootstrap, Namespace namespace, ApplicationConfiguration applicationConfiguration) throws Exception
    {
        //todo: move and merge with app setup
        Injector injector = Guice.createInjector(new ApplicationModule(applicationConfiguration));
        initializeTasks(applicationConfiguration, injector);
    }
}
