package jp.sourceforge.glad.org.seasar.framework.model.dao.mock;

import java.util.LinkedHashMap;
import java.util.Map;

import jp.sourceforge.glad.org.seasar.framework.model.dao.PersonDao;
import jp.sourceforge.glad.org.seasar.framework.model.domain.Person;

import org.seasar.framework.beans.util.Beans;

public class MockPersonDao implements PersonDao {

    final Map<String, Person> people = new LinkedHashMap<String, Person>();

    public synchronized Person getByName(final String name) {
        return people.get(name);
    }

    public synchronized int insert(final Person person) {
        final String name = person.getName();
        if (people.containsKey(name)) {
            throw new RuntimeException("Person already exist: name=" + name);
        }
        people.put(name, new Person(person));
        return 1;
    }

    public synchronized int update(final Person person) {
        final String name = person.getName();
        final Person target = people.get(name);
        if (target == null) {
            return 0;
        }
        Beans.copy(person, target).execute();
        return 1;
    }

    public synchronized int delete(final Person person) {
        final String name = person.getName();
        final Person old = people.remove(name);
        return (old == null ? 0 : 1);
    }

}
