/**
 * JOnAS
 * Copyright (C) 2010 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.audit.internal.logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.management.InstanceNotFoundException;
import javax.management.MBeanException;
import javax.management.RuntimeOperationsException;
import javax.management.modelmbean.InvalidTargetObjectTypeException;

import org.apache.commons.modeler.BaseModelMBean;

/**
 * MBean commons modeler adapter for the Audit Log service.
 * @author Florent Benoit
 */
public class AuditLogServiceAdapter extends BaseModelMBean {

    /**
     * Create the mbean.
     * @throws MBeanException if the super constructor fails.
     */
    public AuditLogServiceAdapter() throws MBeanException {
        super();
    }

    /**
     * @return the wrapped resource (managed object)
     */
    protected AuditLogService getManagedComponent() {
        try {
            return (AuditLogService) getManagedResource();
        } catch (InstanceNotFoundException e) {
            throw new IllegalStateException("Cannot get the managed resource of the MBean", e);
        } catch (RuntimeOperationsException e) {
            throw new IllegalStateException("Cannot get the managed resource of the MBean", e);
        } catch (MBeanException e) {
            throw new IllegalStateException("Cannot get the managed resource of the MBean", e);
        } catch (InvalidTargetObjectTypeException e) {
            throw new IllegalStateException("Cannot get the managed resource of the MBean", e);
        }
    }

    /**
     * Calls some operation on the wrapped object.
     * @param registrationDone if registration has been done or not
     */
    @Override
    public void postRegister(final Boolean registrationDone) {
        //
    }

    /**
     * @return the IDs of the nodes that are at the root level.
     */
    public String[] getRootNodesID() {
        List<String> ids = new ArrayList<String>();
        LinkedList<NodeReport> list = getManagedComponent().getNodeReports();

        if (list != null) {
            // Add in the reverse order (first element will be the last result)
            ListIterator<NodeReport> listIterator = list.listIterator(list.size());
            while (listIterator.hasPrevious()) {
                NodeReport node = listIterator.previous();
                if (!node.isMissingParent()) {
                    ids.add(node.getID());
                }

            }
        }
        return ids.toArray(new String[ids.size()]);
    }

    /**
     * @param id the given node ID
     * @return the description for the given node
     */
    public Map<String, Object> getDescriptionNodeId(final String id) {
        Map<String, Object> description = new HashMap<String, Object>();

        NodeReport node = getManagedComponent().search(id, true);

        // N/A, return null
        if (node == null) {
            return null;
        }

        // date
        description.put("date", node.getDate());

        // name
        description.put("name", node.getName());

        // name
        description.put("application", node.getApplication());

        // desc
        description.put("desc", node.getDesc());

        // type
        description.put("type", node.getType().toString());

        // execTime
        description.put("execTime", node.getExecTime());

        // children ids in the correct order
        TreeMap<Integer, NodeReport> map = node.getTreeMap();
        Set<Map.Entry<Integer, NodeReport>> entries = map.entrySet();
        List<String> children = new ArrayList<String>();
        for (Map.Entry<Integer, NodeReport> nodeEntry : entries) {
            children.add(nodeEntry.getValue().getID());
        }
        description.put("children", children.toArray(new String[children.size()]));

        // depth
        description.put("depth", getDepth(node));


        return description;
    }

    /**
     * Depth of a node.
     * @param node the node to compute
     * @return the depth of the given node
     */
    protected int getDepth(final NodeReport node) {
        int count = 1;
        TreeMap<Integer, NodeReport> map = node.getTreeMap();
        Set<Map.Entry<Integer, NodeReport>> entries = map.entrySet();
        int max = 0;
        for (Map.Entry<Integer, NodeReport> nodeEntry : entries) {
            int tmp =  getDepth(nodeEntry.getValue());
            if (tmp > max) {
                max = tmp;
            }
        }
        // add the maximum depth of each child
        count += max;
        return count;
    }

}
