package jp.sourceforge.glad.org.seasar.framework.model.repository.impl;

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

/**
 * @author GLAD!!
 */
public class PersonRepositoryImpl implements PersonRepository {

    PersonDao personDao;

    ModelHelper modelHelper;

    public Person getPerson(final String name) {
        final Person person = personDao.getByName(name);
        // DAOにModelFactoryを組み込んだ方がベター。
        modelHelper.injectDependency(person);
        return person;
    }

    public void savePerson(final Person person) {
        final String name = person.getName();
        final Person old = personDao.getByName(name);
        int result;
        if (old == null) {
            result = personDao.insert(person);
        } else {
            result = personDao.update(person);
        }
        if (result != 1) {
            throw new RuntimeException("couldn't save Person: " + person);
        }
    }

    public void setPersonDao(PersonDao personDao) {
        this.personDao = personDao;
    }

    public void setModelHelper(ModelHelper modelHelper) {
        this.modelHelper = modelHelper;
    }

}
