/*
 * 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.registrationvalidation;

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 page for the RegistrationValidationMail
 * 
 * @author s_wolff
 */
class RegistrationValidationMailPreview extends BasePage
{
	private static final long serialVersionUID = 1L;

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

	RegistrationValidationMailPreview(final TemporaryMail mail)
	{
		super(null);
		final int runAndDineId = mail.getRunAndDineId();

		Date currentDate = new Date();
		Date registrationDeadline;
		try
		{
			registrationDeadline = RDManager.getInstance().getById(runAndDineId).getRegistrationDeadline();
		}
		catch (ModelNotExistingException e)
		{
			LOG.error("ModelNotExistingException");
			throw new AbortWithHttpErrorCodeException(404);
		}

		WebMarkupContainer warning = new WebMarkupContainer("warning");
		warning.setVisible(currentDate.before(registrationDeadline));
		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 RegistrationValidationMailEditor(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);
	}
}
