/*
 * Copyright 2012 s_wolff.
 *
 * 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 org.aegee.runanddine.feedback;

import java.util.Date;

import org.aegee.runanddine.BasePage;
import org.aegee.runanddine.OverviewPage;
import org.aegee.runanddine.runanddine.RDManager;
import org.aegee.runanddine.util.data.ModelNotExistingException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.apache.wicket.request.http.flow.AbortWithHttpErrorCodeException;

/**
 * Preview for GracefulMailOfThanksMail
 * 
 * @author s_wolff
 */
class GracefulMailOfThanksMailPreview extends BasePage
{
	private static final long serialVersionUID = 1L;

	private static final Log LOG = LogFactory.getLog(GracefulMailOfThanksMailPreview.class);

	/**
	 * Page constructor for TemporaryMail
	 * 
	 * @param mail
	 *            TemporaryMail to be previewed
	 */
	GracefulMailOfThanksMailPreview(final TemporaryMail mail)
	{
		super(null);

		Date currentDate = new Date();
		Date runAndDineDate;
		try
		{
			runAndDineDate = RDManager.getInstance().getById(mail.getRunAndDineId()).getDate();
		}
		catch (ModelNotExistingException e)
		{
			LOG.error("ModelNotExistingException");
			throw new AbortWithHttpErrorCodeException(404);
		}

		WebMarkupContainer warning = new WebMarkupContainer("warning");
		warning.setVisible(currentDate.before(runAndDineDate));
		this.add(warning);

		Form<Void> form = new Form<Void>("form")
		{

			@Override
			protected void onSubmit()
			{
				super.onSubmit();
				mail.send();
				super.setResponsePage(OverviewPage.class, null);
			}
		};
		form.add(new Label("subject", mail.getRenderedSubject()));
		Link backLink = new Link("backLink")
		{

			@Override
			public void onClick()
			{
				this.setResponsePage(new GracefulMailOfThanksMailEditor(mail));
			}
		};
		form.add(backLink);

		String contentLines[] = mail.getRenderedContent().split("\n");
		RepeatingView rv = new RepeatingView("content");
		for (int i = 0; i < contentLines.length; i++)
		{
			rv.add(new Label(rv.newChildId(), contentLines[i]));
			rv.add(new Label(rv.newChildId(), "<br>").setEscapeModelStrings(false));
		}
		form.add(rv);

		this.add(form);
	}
}
