package it.mice.voila.runtime.hibernate.bag;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.collection.PersistentCollection;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.usertype.UserCollectionType;

/**
 * Created by IntelliJ IDEA.
 * User: zzy9v4
 * Date: 20-feb-2007
 * Time: 13.47.23
 * To change this template use File | Settings | File Templates.
 */
public class CustomBagType implements UserCollectionType {
    public CustomBagType() {
    }

    public PersistentCollection instantiate(SessionImplementor session, CollectionPersister persister) throws HibernateException {
        return new CustomPersistentBag(session, persister);
    }

    public Object instantiate(int anticipatedSize) {
        return anticipatedSize <= 0 ? new ArrayList() : new ArrayList( anticipatedSize + 1 );
    }

    public PersistentCollection wrap(SessionImplementor session, Object collection) {
        return new CustomPersistentBag(session, (Collection) collection);
    }

    public Iterator getElementsIterator(Object collection) {
        return ((List) collection).iterator();
    }

    public boolean contains(Object collection, Object entity) {
        List set = (List) collection;
        return set.contains(entity);
    }

    public Object indexOf(Object collection, Object entity) {
        List list = (List) collection;
        int i = list.indexOf(entity);
        if (i == -1) {
            return null;
        } else {
            return new Integer(i);
        }
    }

    public Object replaceElements(Object original, Object target, CollectionPersister persister, Object owner, Map copyCache, SessionImplementor session) throws HibernateException {
        List originalList = (List) original;
        List targetList = (List) target;
        targetList.clear();
        targetList.addAll(originalList);
        return target;
    }
}
