package se.chalmers.dat255.grupp12;
import java.sql.SQLException;
/**
* Date: 2013-10-16
* Time: 16:07
*/
public class ListCommitHandler extends CommitHandler {
public ListCommitHandler(ClientChangeList changes, User user) {
super(changes,user);
}
/**
* Insert a new list to the database
*
* @param m - The modification containing the needed information
*/
@Override
public void insert(Modification m) {
TaskList oldList = m.getList(); // Negative reference ids from client
try {
int oldListId = oldList.getId();
TaskList newList = db.insertList(oldList, user);
changes.addIdChange(oldListId, newList.getId()); // Add an id change to the list of id changes
} catch (SQLException e) {
e.printStackTrace();
}
}
private int getListId(Modification m) {
int id = m.getListId();
if (id < 1) {
id = changes.getNewId(id); // Occurs when the list is created and changed in the same sync.
}
return id;
}
/**
* Update an existing list on the database
* The modification handled contains a Change which contains a String type
* which tells what type of update is to be made
* The list is updated accordingly
*
* @param m - The modification containing the needed information
*/
@Override
public void update(Modification m) {
try {
int listId = getListId(m);
TaskList list = db.getList(listId); // Client sends invalid id to server, we need to look them up
String newValue = m.getChange().getTo();
String type = m.getChange().getType();
switch (type) {
case Constants.LIST_TITLE:
list.setName(newValue);
break;
case Constants.LIST_ADDUSER:
try {
db.assignUserToList(db.getUser(newValue), list.getId()); // New value is user's mail
} catch (DataNotFoundException e) {
System.err.println("User not found in db -- No danger on the roof!");
}
return; // No update in 'lists' table required
default:
throw new UnsupportedOperationException("List change property not implemented:" + type);
}
db.updateList(listId, list);
} catch (SQLException | DataNotFoundException e) {
e.printStackTrace();
}
}
/**
* Removes a list from the database
*
* @param m - The modification containing the needed information
*/
@Override
public void delete(Modification m) {
try {
int listId = getListId(m);
if (db.getUsers(listId).size() > 1) {
db.removeUserFromList(user.getId(), listId);
} else {
db.deleteList(listId);
}
} catch (SQLException | DataNotFoundException e) {
e.printStackTrace();
}
}
}