/*
 * JBoss, Home of Professional Open Source
 * Copyright 2006, Red Hat Middleware LLC, and individual contributors
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This 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 (at your option) any later version.
 *
 * This software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.managed.plugins;

import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.Set;

import org.jboss.managed.api.ComponentType;
import org.jboss.managed.api.ManagedDeployment;
import org.jboss.managed.api.ManagedObject;
import org.jboss.managed.api.ManagedOperation;
import org.jboss.managed.api.ManagedProperty;
import org.jboss.managed.api.MutableManagedComponent;
import org.jboss.managed.api.MutableManagedObject;
import org.jboss.managed.api.RunState;
import org.jboss.managed.api.RunStateMapper;
import org.jboss.managed.api.annotation.RunStateProperty;
import org.jboss.metatype.api.values.MetaValue;

/**
 * Managed component impl.
 *
 * @author Scott.Stark@jboss.org
 * @version $Revision: 89227 $
 */
public class ManagedComponentImpl extends DelegateManagedCommonImpl
   implements MutableManagedComponent, Serializable
{
   private static final long serialVersionUID = 1;
   
   private ManagedDeployment owner;
   private ComponentType type;
   private RunState runState = RunState.UNKNOWN;
   private transient RunStateMapper stateMapper;
   private transient ManagedProperty stateProperty;
   
   public ManagedComponentImpl(ComponentType type, ManagedDeployment owner, ManagedObject mo)
   {
      this(type, owner, mo, null);
   }
   public ManagedComponentImpl(ComponentType type, ManagedDeployment owner, ManagedObject mo,
         RunStateMapper stateMapper)
   {
      super(mo);
      this.type = type;
      this.owner = owner;
      this.stateMapper = stateMapper;
      // Determine what the run state property is
      Map<String, ManagedProperty> props = mo.getProperties();
      if(props != null)
      {
         for(ManagedProperty prop : props.values())
         {
            if(prop.hasAnnotation(RunStateProperty.class.getName()))
            {
               stateProperty = prop;
               if(stateMapper == null)
               {
                  // Try to create it from the RunStateProperty
                  RunStateProperty rsp = (RunStateProperty) prop.getAnnotations().get(RunStateProperty.class.getName());
                  String[] metaValues = rsp.metaValues();
                  String[] enumValues = rsp.enumValues();
                  try
                  {
                     Constructor<? extends RunStateMapper> ctor = rsp.value().getConstructor(metaValues.getClass(), enumValues.getClass());
                     this.stateMapper = ctor.newInstance(metaValues, enumValues);
                  }
                  catch (Exception e)
                  {
                     try
                     {
                        this.stateMapper = rsp.value().newInstance();
                     }
                     catch (Exception e1)
                     {
                     }
                  }
               }
               // Cache the run state
               runState = updateRunState();
               break;
            }
         }
      }
   }

   public Map<String, Annotation> getAnnotations()
   {
      return getDelegate().getAnnotations();
   }

   public RunStateMapper getStateMapper()
   {
      return stateMapper;
   }
   public void setStateMapper(RunStateMapper stateMapper)
   {
      this.stateMapper = stateMapper;
   }

   public RunState getRunState()
   {
      return runState;
   }
   public void setRunState(RunState runState)
   {
      this.runState = runState;
   }

   public void setOperations(Set<ManagedOperation> operations)
   {
      ManagedObject mo = getDelegate();
      if(mo instanceof MutableManagedObject)
      {
         MutableManagedObject mmo = MutableManagedObject.class.cast(mo);
         mmo.setOperations(operations);
      }
   }
   public void setProperties(Map<String, ManagedProperty> properties)
   {
      ManagedObject mo = getDelegate();
      if(mo instanceof MutableManagedObject)
      {
         MutableManagedObject mmo = MutableManagedObject.class.cast(mo);
         mmo.setProperties(properties);
      }      
   }

   /**
    * Update the cached run state
    * @return the updated cache state
    */
   public RunState updateRunState()
   {
      RunState state = RunState.UNKNOWN;
      if(stateMapper != null && stateProperty != null)
      {
         MetaValue value = stateProperty.getValue();
         state = stateMapper.getRunState(stateProperty, value);
         this.runState = state;
      }
      return runState;
   }

   /**
    * Update the component statistic property values. This needs to be
    * overriden by a subclass in the runtime environment to provide a useful
    * implementation.
    * @return false always.
    */
   public boolean update()
   {
      return false;
   }

   public ManagedDeployment getDeployment()
   {
      return owner;
   }
   
   public ComponentType getType()
   {
      return type;
   }
   
   public String toString()
   {
      StringBuilder tmp = new StringBuilder(super.toString());
      tmp.append('{');
      tmp.append("name=");
      tmp.append(super.getName());
      tmp.append(", type=");
      tmp.append(type);
      tmp.append(", owner=ManagedDeployment@");
      tmp.append(System.identityHashCode(owner));
      tmp.append('}');
      return tmp.toString();
   }
}
