package org.iri_research.renkan.management;

import org.iri_research.renkan.models.Project;
import org.iri_research.renkan.models.RenkanUser;
import org.iri_research.renkan.models.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.shell.core.CommandMarker;
import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.stereotype.Component;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.WriteConcern;

@Component
public class MigrateRenkanUser implements CommandMarker {

    @CliAvailabilityIndicator({"migrate-renkan-user"})
    public boolean isCommandAvailable() {
        return true;
    }

    @Autowired
    private MongoTemplate template;

    @CliCommand(value="migrate-renkan-user", help="Migrate Renkan User")
    public void start() {

        DBCollection userColl = template.getCollection(template
                .getCollectionName(User.class));
        DBCollection renkanUserColl = template.getCollection(template
                .getCollectionName(RenkanUser.class));
        DBCollection projectColl = template.getCollection(template
                .getCollectionName(Project.class));

        for (DBObject user : userColl.find()) {
            if (!user.containsField("project_id")) {
                continue;
            }
            String projectId = (String) user.get("project_id");
            if (projectId == null || projectId.isEmpty()) {
                user.removeField("project_id");
                userColl.save(user);
                continue;
            }
            DBObject proj = new BasicDBObject();
            proj.put("_id", projectId);
            if (projectColl.findOne(proj) != null) {
                DBObject renkanUser = new BasicDBObject();
                renkanUser.put("project_id", projectId);
                renkanUser.put("user_id", user.get("_id"));
                if (renkanUserColl.findOne(renkanUser) == null) {
                    System.out.println(String.format("%s : %s : %s",
                            user.get("_id"), user.get("title"),
                            user.get("project_id")));
                    renkanUser = new BasicDBObject();
                    renkanUser.put("project_id", user.get("project_id"));
                    renkanUser.put("user_id", user.get("_id"));
                    renkanUser.put("color", user.get("color"));
                    renkanUserColl.insert(renkanUser);
                }
                user.removeField("project_id");
                userColl.save(user);
            } else {
                userColl.remove(user, WriteConcern.ACKNOWLEDGED);
            }
        }

    }
}
