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.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.mongodb.core.MongoTemplate;
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 {

    public static void main(String[] args) {

        @SuppressWarnings("resource")
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "classpath:WEB-INF/applicationContext.xml");

        MigrateRenkanUser p = context.getBean(MigrateRenkanUser.class);
        p.start(args);

    }

    @Autowired
    private MongoTemplate template;

    private void start(String[] args) {

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

    }
}
