package nl.xs4all.banaan.tap.web;

import nl.xs4all.banaan.tap.web.layout.DateTimeConverter;
import nl.xs4all.banaan.tap.web.searchpage.HomePage;

import org.apache.wicket.ConverterLocator;
import org.apache.wicket.IConverterLocator;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.request.Url;
import org.apache.wicket.request.resource.UrlResourceReference;
import org.apache.wicket.spring.injection.annot.SpringComponentInjector;
import org.joda.time.DateTime;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class WicketApplication extends WebApplication implements ApplicationContextAware {

    public static final String JQUERY = "js/libs/jquery-1.8.2.js";

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public Class<? extends WebPage> getHomePage() {
        return HomePage.class;
    }

    @Override
    public void init() {
        super.init();
        setJQueryLocation(JQUERY);
        setComponentInjector();
    }


    @Override
    protected IConverterLocator newConverterLocator() {
        final ConverterLocator cl = (ConverterLocator) super.newConverterLocator();
        cl.set(DateTime.class, new DateTimeConverter());
        return cl;
    }


    private void setComponentInjector() {
        // Ensure injector gets a context both when started from servlet
        // container and when started from SpringJUnit4ClassRunner
        // http://blog.comsysto.com/2010/06/04/test-driven-development-with-apache-wicket-and-spring-framework/
        getComponentInstantiationListeners()
            .add(new SpringComponentInjector(this, applicationContext));
    }

    // use jquery shared with bootstrap
    private void setJQueryLocation(final String jqueryLocation) {
        Url url = Url.parse(jqueryLocation);
        UrlResourceReference reference = new UrlResourceReference(url);
        getJavaScriptLibrarySettings().setJQueryReference(reference);
    }

}
