/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package woolpack.samples.crud;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SampleBeanTable implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private final Map<Integer, SampleBean> map;
	private int nextId;
	
	public SampleBeanTable() {
		map = new HashMap<Integer, SampleBean>();
		nextId = 0;
	}
	
	public void register(final SampleBean bean) {
		synchronized (this) {
			bean.setUserId(nextId++);
			map.put(Integer.valueOf(bean.getUserId()), bean);
		}
	}
	
	public List<SampleBean> searchList(final String name) {
		synchronized (this) {
			final List<SampleBean> result = new ArrayList<SampleBean>();
			for (final SampleBean bean : map.values()) {
				if (bean.getName().startsWith(name)) {
					result.add(bean);
				}
			}
			return result;
		}
	}
	
	public SampleBean searchOne(final int id) {
		synchronized (this) {
			final SampleBean bean = map.get(id);
			bean.getClass();
			return bean;
		}
	}
	
	public void update(final SampleBean bean) {
		synchronized (this) {
			map.get(bean.getUserId()).getClass();
			map.put(bean.getUserId(), bean);
		}
	}
	
	public void delete(final int id) {
		synchronized (this) {
			map.get(id).getClass();
			map.remove(id);
		}
	}
}
