package com.shin1ogawa.entity;

import java.io.Serializable;

import javax.jdo.PersistenceManager;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import javax.jdo.annotations.Transactional;

import org.apache.commons.lang.builder.ToStringBuilder;

import com.google.appengine.api.datastore.Key;

/**
 * Keyを自動生成するEntity.
 * 
 * @author shin1ogawa
 */
@SuppressWarnings("serial")
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class OtherA implements Serializable {
	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	private Key key;

	@Persistent
	private long code;

	@Persistent
	private String value;

	public Key getKey() {
		return key;
	}

	public void setKey(Key key) {
		this.key = key;
	}

	public long getCode() {
		return code;
	}

	public OtherA setCode(long code) {
		this.code = code;
		return this;
	}

	public String getValue() {
		return value;
	}

	public OtherA setValue(String value) {
		this.value = value;
		return this;
	}

	public OtherA save(PersistenceManager pm) {
		OtherA persist = pm.makePersistent(this);
		this.code = this.key.getId();
		return persist;
	}

	/**
	 * {@link Transactional}が有効ならExceptionが投げられる(別EntityGroupを扱うため)はずだが、
	 * そのようにならない。
	 * 
	 * @param pm
	 * @param entities
	 * @return
	 */
	@Transactional
	public OtherA[] saveAll(PersistenceManager pm, OtherA... entities) {
		if (entities == null || entities.length == 0) {
			throw new IllegalArgumentException();
		}
		OtherA[] results = new OtherA[entities.length];
		for (int i = 0; i < entities.length; i++) {
			results[i] = pm.makePersistent(entities[i]);
			entities[i].setCode(entities[i].getKey().getId());
		}
		return results;
	}

	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}
}
