package org.iri_research.renkan.coweb.event;

import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.inject.Named;

import org.coweb.CowebException;
import org.iri_research.renkan.models.Project;
import org.iri_research.renkan.models.User;
import org.iri_research.renkan.repositories.IRenkanRepository;
import org.iri_research.renkan.repositories.UsersRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Named
public class UserSyncEventManager extends AbstractSyncEventManager<User, String> {

	private final Logger logger = LoggerFactory.getLogger(UserSyncEventManager.class);
	
	private final static String DEFAULT_COLOR = "#000080"; 

	@Inject
	private UsersRepository usersRepository;
		
	public UsersRepository getUsersRepository() {
		return this.usersRepository;
	}
	
	@Override
	public IRenkanRepository<User, String> getObjectRepository() {
		return this.getUsersRepository();
	}


	@Override
	public void insert(String clientId, Map<String, Object> data) {
	
		// get project
		this.logger.debug("UserSyncEventManager: insert User");
		
		@SuppressWarnings("unchecked")
		Map<String, Object> values = (Map<String, Object>) data.get("value");
		String project_id = (String) values.get("_project_id");

		Project project = this.getProjectsRepository().findOne(project_id);
				
		if (null == project) {
			throw new CowebException("user insert: project not found", String.format("Project %s not found", project_id));
		}
		
		String user_id = (String)values.get("id");
		String color = (String)values.get("color");
		if(color == null || color.length() == 0) {
			color = UserSyncEventManager.DEFAULT_COLOR;
		}
		
		User user = new User(user_id, (String)values.get("title"), (String)values.get("description"), (String)values.get("uri"), color, project_id);
		
		Integer position = (Integer)data.get("position");
		
		if(position == null || position < 0) {
			throw new CowebException("node insert: bad insert position", String.format("Bad position %s not found", position==null?"null":position.toString()));
		}
		int index = position.intValue();
		List<User> users = project.getUsers();
		if(index > users.size()) {
			index = users.size();
		}
		users.add(index,user);

		this.getUsersRepository().save(user);
		this.getProjectsRepository().save(project);
		
	}

	@Override
	public void nullOperation(String clientId, Map<String, Object> data) {
		this.logger.debug("nullOperation: NOP");
	}

	@Override
	protected List<User> getObjectList(Project project) {
		return project.getUsers();
	}

}
