/**
 *
 */
package jp.agentec.sinaburocast.action.admin.mail;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.mail.MessagingException;

import jp.agentec.sinaburocast.action.AbstractAction;
import jp.agentec.sinaburocast.common.SinaburoConstant;
import jp.agentec.sinaburocast.common.SinaburoConstant.MailSendTypeStr;
import jp.agentec.sinaburocast.common.annotation.OperationHistoryAno;
import jp.agentec.sinaburocast.common.util.MailUtil;
import jp.agentec.sinaburocast.common.util.PropertyUtil;
import jp.agentec.sinaburocast.common.util.SinaburoUtil;
import jp.agentec.sinaburocast.common.util.SinaburoViewUtil;
import jp.agentec.sinaburocast.entity.AdminUser;
import jp.agentec.sinaburocast.entity.DeliveryGroup;
import jp.agentec.sinaburocast.entity.DeliveryGroupMember;
import jp.agentec.sinaburocast.entity.Enquete;
import jp.agentec.sinaburocast.entity.EnqueteMail;
import jp.agentec.sinaburocast.form.admin.mail.MailRegistForm;
import jp.agentec.sinaburocast.service.DeliveryGroupMemberService;
import jp.agentec.sinaburocast.service.DeliveryGroupService;
import jp.agentec.sinaburocast.service.EnqueteMailAddressTmpService;
import jp.agentec.sinaburocast.service.EnqueteMailService;
import jp.agentec.sinaburocast.service.EnqueteService;

import org.apache.commons.validator.GenericValidator;
import org.apache.log4j.Logger;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.TokenProcessor;
import org.seasar.framework.util.StringUtil;
import org.seasar.struts.annotation.ActionForm;
import org.seasar.struts.annotation.Execute;

/**
 * @author kim-hs
 * アンケートメール編集
 *
 */
public class MailEditAction extends AbstractAction {

	private final Logger logger = Logger.getLogger(getClass());

	@ActionForm
	public MailRegistForm mailRegistForm;

	public DeliveryGroupService deliveryGroupService;

	public DeliveryGroupMemberService deliveryGroupMemberService;

	public EnqueteMailService enqueteMailService;

	public EnqueteService enqueteService;

	public EnqueteMailAddressTmpService enqueteMailAddressTmpService;

	/**
	 * 編集対象のアンケートメール検索
	 *
	 */
	@Execute(validator = false)
	public String index() {
		List<DeliveryGroup> deliveryGroupList = deliveryGroupService.findAllOrderById();

		session.setAttribute("deliveryGroupList", deliveryGroupList);

		mailRegistForm.sender =  PropertyUtil.getProperty("email.sender.address");

		EnqueteMail info = enqueteMailService.findById(Integer.parseInt(mailRegistForm.enqueteMailId));

		mailRegistForm.enqueteMailId = info.enqueteMailId.toString();
		mailRegistForm.status = info.status.toString();
		mailRegistForm.subject = info.subject;

		if (info.enqueteId != null) {
			mailRegistForm.enqueteId = info.enqueteId.toString();
			mailRegistForm.sendType = MailSendTypeStr.FILE_UPLOAD;
		} else {
			mailRegistForm.deliveryGroupId = info.deliveryGroupId.toString();
			mailRegistForm.sendType = MailSendTypeStr.GROUP;
		}

		mailRegistForm.mailBody = info.mailBody;
		mailRegistForm.deliveryTargetType = info.deliveryTargetType;
		mailRegistForm.deliveryTargetMethod = info.deliveryTargetMethod;
		if (!StringUtil.isBlank(info.deliveryTargetMethod)) {
			if (info.deliveryTargetMethod.equals("0") && info.deliveryDate != null) {
				String strdate = info.deliveryDate.toString();
				mailRegistForm.deliveryDate = strdate.substring(0,10).replace("-", "/");
				if (strdate.substring(11,12).equals("0")) {
					mailRegistForm.deliveryHour = strdate.substring(12,13);
				} else {
					mailRegistForm.deliveryHour = strdate.substring(11,13);
				}
				mailRegistForm.deliveryMin = strdate.substring(14,16);
			}
		}
		//mailRegistForm.enqueteMailId = null;
		return "/admin/mail/mailEdit.html";
	}

	/**
	 * テストメール送信
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 */
	@Execute(validator = true, input="/admin/mail/mailEdit.html")
	public String testMailSend() throws UnsupportedEncodingException, MessagingException{

		//メール送信
		try {
			MailUtil.send(mailRegistForm.testMail,mailRegistForm.subject, mailRegistForm.mailBody);
		} catch (MessagingException e) {
			logger.warn("Mail send failed." + e.toString());
			addErrorMessage("testMail", SinaburoViewUtil.getMessage("errors.E055"));
			return "/admin/mail/mailEdit.html";
		}

		return "/admin/mail/mailEdit.html";
	}

	/**
	 * 一時保存
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 */
	@Execute(validator = false)
	@OperationHistoryAno(operationTypeId=SinaburoConstant.OperationType.INSERT,target="メール一時保存",detail="一時保存",screenId=SinaburoConstant.screenId.CMS0009)
	public String saveMail() throws UnsupportedEncodingException, MessagingException{
		if (mailRegistForm.sendType.equals(MailSendTypeStr.FILE_UPLOAD)) {
			if(mailRegistForm.enqueteId.equals("")){
				ActionMessages messages = (ActionMessages) request.getAttribute(Globals.ERROR_KEY);
				if (messages == null) {
					messages = new ActionMessages();
				}
				messages.add("enqueteId", new ActionMessage(SinaburoViewUtil.getMessage("errors.E064")));
				request.setAttribute(Globals.ERROR_KEY, messages);
				return "/admin/mail/mailEdit.html";
			}
			if(!GenericValidator.isInt(mailRegistForm.enqueteId)){
				ActionMessages messages = (ActionMessages) request.getAttribute(Globals.ERROR_KEY);
				if (messages == null) {
					messages = new ActionMessages();
				}messages.add("enqueteId", new ActionMessage(SinaburoViewUtil.getMessage("errors.integer", SinaburoViewUtil.getMessage("labels.enqueteId"))));
				request.setAttribute(Globals.ERROR_KEY, messages);
				return "/admin/mail/mailEdit.html";
			}
			Enquete enquete = enqueteService.findById(Integer.parseInt(mailRegistForm.enqueteId));
			if(enquete == null){
				ActionMessages messages = (ActionMessages)request.getAttribute(Globals.ERROR_KEY);
				if (messages == null) {
					messages = new ActionMessages();
				}
				messages.add("enqueteId", new ActionMessage(SinaburoViewUtil.getMessage("errors.E063")));
				request.setAttribute(Globals.ERROR_KEY, messages);
				return "/admin/mail/mailEdit.html";
			}
		} else {
			if (mailRegistForm.deliveryGroupId.equals("")) {
				ActionMessages messages = (ActionMessages) request.getAttribute(Globals.ERROR_KEY);
				if (messages == null) {
					messages = new ActionMessages();
				}
				messages.add("deliveryGroupId", new ActionMessage(SinaburoViewUtil.getMessage("errors.E032")));
				request.setAttribute(Globals.ERROR_KEY, messages);
				return "/admin/mail/mailEdit.html";
			}
		}

		AdminUser adminUser = getAdmin();

		EnqueteMail enqueteMail = new EnqueteMail();
		enqueteMail.status = Integer.parseInt(mailRegistForm.status);
		enqueteMail.subject = mailRegistForm.subject;
		if (!mailRegistForm.sendType.equals(MailSendTypeStr.FILE_UPLOAD)) {
			enqueteMail.deliveryGroupId = Integer.parseInt(mailRegistForm.deliveryGroupId);
		} else {
			enqueteMail.enqueteId = Integer.parseInt(mailRegistForm.enqueteId);
		}
		enqueteMail.mailBody = mailRegistForm.mailBody;
		enqueteMail.deliveryTargetType =mailRegistForm.deliveryTargetType;
		enqueteMail.deliveryTargetMethod = mailRegistForm.deliveryTargetMethod;

		enqueteMail.deliveryDate =
				SinaburoUtil.convertStringToTimestamp(mailRegistForm.deliveryDate +" "+ mailRegistForm.deliveryHour +":"+mailRegistForm.deliveryMin +":00", "yyyy-MM-dd HH:mm:ss");

		Integer enqueteId = null;

		if (StringUtil.isBlank(mailRegistForm.enqueteMailId)) {
			enqueteId = enqueteMailService.insertEnqueteMail(enqueteMail,adminUser.loginId);
			mailRegistForm.enqueteMailId = String.valueOf(enqueteId);
		} else {
			EnqueteMail info = enqueteMailService.findById(Integer.parseInt(mailRegistForm.enqueteMailId));
			enqueteMail.enqueteMailId = Integer.parseInt(mailRegistForm.enqueteMailId);
			enqueteMail.version = info.version;
			enqueteMail.insertDate = info.insertDate;
			enqueteMail.insId = info.insId;
			enqueteMailService.update(enqueteMail, adminUser.loginId);
			mailRegistForm.enqueteMailId = String.valueOf(info.enqueteMailId);
		}

		return "/admin/mail/mailEdit.html";
	}

	/**
	 * メール作成チェック
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 */
	@Execute(validator = true, input="/admin/mail/mailEdit.html", validate="validate")
	public String confirm(){

		TokenProcessor.getInstance().saveToken(request);

		if(StringUtil.isNotBlank(mailRegistForm.deliveryDate) && !SinaburoUtil.checkDate(mailRegistForm.deliveryDate)){
			ActionMessages messages = (ActionMessages)request.getAttribute(Globals.ERROR_KEY);
			if (messages == null) {
				messages = new ActionMessages();
			}
			messages.add("deliveryDate", new ActionMessage(SinaburoViewUtil.getMessage("errors.E033")));
			addErrorMessage("deliveryDate_1", "errors.E033_1");
			addErrorMessage("deliveryDate_2", "errors.E033_2");
			request.setAttribute(Globals.ERROR_KEY, messages);

			return "/admin/mail/mailEdit.html";
		}

		//時間指定の過去のチェック
		if (mailRegistForm.deliveryTargetMethod.equals("0")) {
			String strTime = mailRegistForm.deliveryDate + SinaburoUtil.LeftPadZero(mailRegistForm.deliveryHour,2)+mailRegistForm.deliveryMin;
			if (SinaburoUtil.strDateCompare(strTime, "yyyy/MM/ddHHmm") != 1) {
				ActionMessages messages = (ActionMessages)request.getAttribute(Globals.ERROR_KEY);
				if (messages == null) {
					messages = new ActionMessages();
				}
				messages.add("deliveryDate", new ActionMessage(SinaburoViewUtil.getMessage("errors.E030")));
				request.setAttribute(Globals.ERROR_KEY, messages);
				return "/admin/mail/mailEdit.html";
			}
		}

		if (mailRegistForm.sendType.equals(MailSendTypeStr.FILE_UPLOAD)) {
			Enquete enquete = enqueteService.findById(Integer.parseInt(mailRegistForm.enqueteId));
			if(enquete == null){
				ActionMessages messages = (ActionMessages)request.getAttribute(Globals.ERROR_KEY);
				if (messages == null) {
					messages = new ActionMessages();
				}
				messages.add("enqueteId", new ActionMessage(SinaburoViewUtil.getMessage("errors.E063")));
				request.setAttribute(Globals.ERROR_KEY, messages);
				return "/admin/mail/mailEdit.html";
			}
			mailRegistForm.enqueteName = enquete.enqueteName;
			mailRegistForm.groupName = "ファイル";
		} else {
			DeliveryGroup deliveryGroup = deliveryGroupService.findById(Integer.parseInt(mailRegistForm.deliveryGroupId));
			mailRegistForm.groupName = deliveryGroup.deliveryGroupName;
		}

		session.setAttribute("mailEdittForm", mailRegistForm);

		return "/admin/mail/mailEditConfirm.html";
	}

	@Resource
	protected Map requestScope;

	/**
	 * アンケートメール登録
	 * @throws Exception
	 */
	@Execute(validator = false)
	@OperationHistoryAno(operationTypeId=SinaburoConstant.OperationType.UPDATE,target="メール編集",detail="更新",screenId=SinaburoConstant.screenId.CMS0011)
	public String regist() throws Exception{
		mailRegistForm = (MailRegistForm)session.getAttribute("mailEdittForm");
    	// トークン確認
   		if (!TokenProcessor.getInstance().isTokenValid(request, true)) {

   			return "/error/admin/doubleAction.html";
    	}

		AdminUser adminUser = getAdmin();

		EnqueteMail enqueteMail = new EnqueteMail();
		//配信方法が時間指定の場合、
		if (mailRegistForm.deliveryTargetMethod.equals("0")) {
			enqueteMail.status = SinaburoConstant.MailStatusType.UNCOMPLETE;
		} else {
			enqueteMail.status = SinaburoConstant.MailStatusType.COMPLETE;
		}

		enqueteMail.subject = mailRegistForm.subject;
		if (mailRegistForm.sendType.equals(MailSendTypeStr.FILE_UPLOAD)) {
			enqueteMail.enqueteId = Integer.parseInt(mailRegistForm.enqueteId);
		} else {
			enqueteMail.deliveryGroupId = Integer.parseInt(mailRegistForm.deliveryGroupId);
		}
		enqueteMail.mailBody = mailRegistForm.mailBody;
		enqueteMail.deliveryTargetType =mailRegistForm.deliveryTargetType;
		enqueteMail.deliveryTargetMethod = mailRegistForm.deliveryTargetMethod;

		enqueteMail.deliveryDate =
				SinaburoUtil.convertStringToTimestamp(mailRegistForm.deliveryDate +" "+ mailRegistForm.deliveryHour +":"+mailRegistForm.deliveryMin +":00", "yyyy-MM-dd HH:mm:ss");
		enqueteMail.enqueteMailId = Integer.parseInt(mailRegistForm.enqueteMailId);

		String serverUrl = PropertyUtil.getString("ENQUETE_SERVER_URL");

		//時間指定の場合
		if (mailRegistForm.deliveryTargetMethod.equals("0") ) {
			EnqueteMail info = enqueteMailService.findById(Integer.parseInt(mailRegistForm.enqueteMailId));
			enqueteMail.version = info.version;
			enqueteMail.insertDate = info.insertDate;
			enqueteMail.insId = info.insId;
			enqueteMailService.update(enqueteMail, adminUser.loginId);

			// ファイルアップロードの場合、メールアドレスを一時的に保存する
			if (mailRegistForm.sendType.equals(MailSendTypeStr.FILE_UPLOAD)) {
				List<DeliveryGroupMember> list = enqueteMailService.fileRead(mailRegistForm.file);
				enqueteMailAddressTmpService.deleteInsert(Integer.parseInt(mailRegistForm.enqueteMailId), list, adminUser.loginId);
			}
		} else {
			//即時送信
			List<DeliveryGroupMember> list;
			if (mailRegistForm.sendType.equals(MailSendTypeStr.FILE_UPLOAD)) {
				list = enqueteMailService.fileRead(mailRegistForm.file);
			} else {
				list = deliveryGroupMemberService.findAllOrderByIdAllList(enqueteMail.deliveryGroupId, null);
			}
			enqueteMailService.insertRegistMailSendLogic(enqueteMail, adminUser.loginId, serverUrl, list);
		}

		return "/admin/mail/mailRegist.html";
	}

	/**
	 * 前の画面に遷移
	 *
	 * @return
	 */
	@Execute(validator = false)
	public String back() {
		mailRegistForm = (MailRegistForm)session.getAttribute("mailEdittForm");
		return "/admin/mail/mailEdit.html";
	}

}