package org.bouncycastle.asn1.cms;

import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.ASN1TaggedObject;
import org.bouncycastle.asn1.BERSequence;
import org.bouncycastle.asn1.BERTaggedObject;
import org.bouncycastle.asn1.DERInteger;
import org.bouncycastle.asn1.DERObject;

public class EncryptedData
{
	private DERInteger            version;
	private EncryptedContentInfo  encryptedContentInfo;
	private ASN1Set               unprotectedAttrs;

	public EncryptedData(
        EncryptedContentInfo    encryptedContentInfo,
        ASN1Set                 unprotectedAttrs)
    {
        if (unprotectedAttrs != null)
        {
            this.version = new DERInteger(2);
        }
        else
        {
            this.version = new DERInteger(0);
        }

		this.encryptedContentInfo = encryptedContentInfo;
		this.unprotectedAttrs = unprotectedAttrs;
	}
	
	public EncryptedData(
        ASN1Sequence seq)
    {
		this.version = (DERInteger)seq.getObjectAt(0);
		this.encryptedContentInfo = EncryptedContentInfo.getInstance(seq.getObjectAt(1));
		if (seq.size() > 2)
        {
			this.unprotectedAttrs = ASN1Set.getInstance((ASN1TaggedObject)seq.getObjectAt(2), false);
		}
	}

    /**
     * return an EncryptedData object from the given object.
     *
     * @param obj the object we want converted.
     * @exception IllegalArgumentException if the object cannot be converted.
     */
	public static EncryptedData getInstance(
        Object obj)
    {
		if (obj == null || obj instanceof EncryptedData)
        {
			return (EncryptedData)obj;
		}
		
		if (obj instanceof ASN1Sequence)
        {
			return new EncryptedData((ASN1Sequence)obj);
		}
		
		throw new IllegalArgumentException(
                "Illegal object in EncryptedData: " + obj.getClass().getName());
	}

	public DERInteger getVersion()
    {
		return version;
	}

	public EncryptedContentInfo getEncryptedContentInfo()
    {
		return encryptedContentInfo;
	}

	public ASN1Set getUnprotectedAttrs()
    {
		return unprotectedAttrs;
	}

    /** 
     * Produce an object suitable for an ASN1OutputStream.
     * <pre>
     * EncryptedData ::= SEQUENCE {
     * 	version CMSVersion,
     * 	encryptedContentInfo EncryptedContentInfo,
     * 	unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL 
     * }
     * </pre>
     */
	public DERObject getDERObject()
    {
        ASN1EncodableVector  v = new ASN1EncodableVector();
		
		v.add(version);
		v.add(encryptedContentInfo);

		if (unprotectedAttrs != null)
        {
			v.add(new BERTaggedObject(false, 1, unprotectedAttrs));
		}
		
		return new BERSequence(v);
	}
}
