/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2012 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.test.multitenant;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.management.ManagementFactory;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ejb.EJB;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ow2.jonas.test.mutlitenant.Author;

/**
 * @author Mohammed Boukada
 */
public class TestServlet extends HttpServlet {

    private Logger logger = Logger.getLogger(TestServlet.class.getName());

    /**
     * Link to the initializer bean.
     */
    @EJB
    private org.ow2.jonas.test.mutlitenant.init.Initializer initializerBean;

    /**
     * Link to the Local Reader bean. Bean will be injected by JOnAS.
     */
    @EJB
    private org.ow2.jonas.test.mutlitenant.reader.LocalReader readerBean;

    @Override
    public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException {

        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        ObjectName name = null;
        try {
            name = new ObjectName("Hello:type=HelloObject");
            org.ow2.jonas.test.mutlitenant.Hello h = new org.ow2.jonas.test.mutlitenant.Hello();
            if (!mbs.isRegistered(name)) {
                mbs.registerMBean(h, name);
            }
        } catch (MalformedObjectNameException e) {
            e.printStackTrace();
        } catch (NotCompliantMBeanException e) {
            e.printStackTrace();
        } catch (InstanceAlreadyExistsException e) {
            e.printStackTrace();
        } catch (MBeanRegistrationException e) {
            e.printStackTrace();
        }

        logger.log(Level.INFO, "This is a log message");

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("TestServlet : Hey !");


        initAuthorBooks(out);
        displayAuthors(out);

        out.close();
    }

    /**
     * Init list of authors/books.
     * @param out the given writer
     */
    private void initAuthorBooks(final PrintWriter out) {
        out.println("Initialize authors and their books...<br/>");

        try {
            initializerBean.initializeEntities();
        } catch (Exception e) {
            displayException(out, "Cannot init list of authors with their books", e);
            return;
        }
    }

    /**
     * Display authors.
     * @param out the given writer
     */
    private void displayAuthors(final PrintWriter out) {
        out.println("Get authors");
        out.println("<br /><br />");

        // Get list of Authors
        List<Author> authors = null;
        try {
            authors = readerBean.listAllAuthors();
        } catch (Exception e) {
            displayException(out, "Cannot call listAllAuthors on the bean", e);
            return;
        }

        // List for each author, the name of books
        if (authors != null) {
            for (Author author : authors) {
                out.println("Author '" + author.getName() + "';");

            }
        } else {
            out.println("No author found !");
        }

    }

    /**
     * If there is an exception, print the exception.
     * @param out the given writer
     * @param errMsg the error message
     * @param e the content of the exception
     */
    private void displayException(final PrintWriter out, final String errMsg, final Exception e) {
        out.println("<p>Exception : " + errMsg);
        out.println("<pre>");
        e.printStackTrace(out);
        out.println("</pre></p>");
    }
}
