package commands;

import com.google.inject.Guice;
import com.google.inject.Injector;
import core.ApplicationConfiguration;
import io.dropwizard.cli.ConfiguredCommand;
import io.dropwizard.setup.Bootstrap;
import modules.ApplicationModule;
import net.sourceforge.argparse4j.inf.Namespace;
import org.mongodb.morphia.Datastore;
import repositories.TeamsRepository;

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

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

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

        teamsRepository.clean();
        applicationConfiguration.getTeams().forEach(team -> {
            team.getMembers().stream().forEach(datastore::save); //todo: use usersrepostiroy to save?
            datastore.save(team);
        });
    }

    @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);
    }
}
