package jp.agentec.sinaburocast.service;

import java.util.ArrayList;
import java.util.List;

import jp.agentec.sinaburocast.entity.DeliveryGroupMember;
import jp.agentec.sinaburocast.entity.EnqueteMailAddressTmp;
import jp.agentec.sinaburocast.entity.Member;

import org.seasar.extension.jdbc.where.SimpleWhere;
import org.seasar.framework.container.annotation.tiger.Component;
import org.seasar.framework.container.annotation.tiger.InstanceType;

@Component(instance = InstanceType.SINGLETON)
public class EnqueteMailAddressTmpService extends AbstractService<EnqueteMailAddressTmp> {

	private static final String ID_SEQ_NAME = "enquete_mail_address_tmp_id_seq";

	@Override
	public int insert(EnqueteMailAddressTmp entity, String insIdStr) {
		entity.enqueteMailAddressTmpId = getSeqNextVal(Long.class, ID_SEQ_NAME);
		return super.insert(entity, insIdStr);
	}

	public List<EnqueteMailAddressTmp> findByEnqueteMailId(Integer enqueteMailId) {
		return select().where(new SimpleWhere().eq("enqueteMailId", enqueteMailId)).getResultList();
	}

	public List<DeliveryGroupMember> findByEnqueteMailIdExchangeDeliveryGroupMember(Integer enqueteMailId) {
		List<DeliveryGroupMember> deliveryGroupMemberList = new ArrayList<DeliveryGroupMember>();
		for (EnqueteMailAddressTmp address : select().where(new SimpleWhere().eq("enqueteMailId", enqueteMailId)).getResultList()) {
			DeliveryGroupMember deliveryGroupMember = new DeliveryGroupMember();
			Member member = new Member();
			member.pcEmail = address.email;
			member.mbEmail = address.email;
			member.firstName = "";
			member.lastName = "";
			member.loginId = "";
			member.password = "";
			member.memberId = null;
			member.pointNum = 0;
			deliveryGroupMember.member = member;
			deliveryGroupMemberList.add(deliveryGroupMember);
		}
		return deliveryGroupMemberList;
	}

	public void deleteByEnqueteMailId(Integer enqueteMailId) {
		List<EnqueteMailAddressTmp> deleteList = findByEnqueteMailId(enqueteMailId);
		if (deleteList != null && deleteList.size() > 0) {
			jdbcManager.deleteBatch(deleteList).execute();
		}
	}

	public void deleteInsert(Integer enqueteMailId, List<DeliveryGroupMember> addressList, String insIdStr) {
		deleteByEnqueteMailId(enqueteMailId);

		for (DeliveryGroupMember address : addressList) {
			EnqueteMailAddressTmp entity = new EnqueteMailAddressTmp();
			entity.enqueteMailId = enqueteMailId;
			entity.email = address.member.pcEmail;
			insert(entity, insIdStr);
		}
	}
}