/**
 * <p>
 * (C) Siemens Aktiengesellschaft, Germany, 2013
 * </p>
 * 
 * <p>created 30.11.2012 - 17:28:40</p>
 * 
 * @since Sol7
 * @author  zelgerpe
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Library General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) 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 Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this program (see the file LICENSE.txt for more
 * details); if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
 */

package org.acplt.oncrpc;
import java.io.IOException;

/**
 * wrapper provides XdrAble for generated java enums.<br/>
 * e.g.:
 * public enum SummaryAlarm implements {@linkplain HasEncoding}<SummaryAlarm> { .. }
 * 
 * @author zelgerpe
 *
 * @param <T> typical an enum class, see above.
 */
public class XdrEnum<T extends HasEncoding<T>> implements XdrAble
{

  private HasEncoding<T> wrapped;
  
  public XdrEnum(T ee)
  {
    assert(ee!=null);
    wrapped=ee;
  }
  public XdrEnum(T ee, XdrDecodingStream xdr)throws OncRpcException, IOException
  {
    this(ee);
    xdrDecode(xdr);
  }
  @Override
  public void xdrEncode(XdrEncodingStream xdr) throws OncRpcException, IOException
  {
    xdr.xdrEncodeInt(wrapped.getEncoding());
  }

  @Override
  public void xdrDecode(XdrDecodingStream xdr) throws OncRpcException, IOException
  {
   int v=xdr.xdrDecodeInt();
   wrapped=create(v, wrapped);
  }  
  
  public HasEncoding<T> getWrapped()
  {
    return wrapped;
  }  
  
  @SuppressWarnings("unchecked")
  public T getValue()
  {
    return (T)wrapped;
  }
  
  @Override
  public String toString()
  {
    return "XdrEnum [wrapped=" + this.wrapped + "]";
  }

  @SuppressWarnings("unchecked")
  static public <T> T create(HasEncoding<T> tt, XdrDecodingStream xdr) throws OncRpcException, IOException
  {
    int v=xdr.xdrDecodeInt();
    return (T)create(v, tt);    
  }

  static public <T> HasEncoding<T> create(int e, HasEncoding<T> tt)  throws OncRpcException
  {
    for(HasEncoding<T> s : tt.getValues())
    {
      if(s.getEncoding()==e)
        return s;
    }
    throw new OncRpcException("can't decode, unexpected value="+e+" for "+tt.getClass().getName());
  }
  
  @SuppressWarnings("unchecked")
  static public <T> T fromEncoding(int e, HasEncoding<T> tt) 
  {
    for(HasEncoding<T> s : tt.getValues())
    {
      if(s.getEncoding()==e)
        return (T)s;
    }
    return (T)tt;
  }

}