/*******************************************************************************
 * Copyright 2008-2010 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use
 * this file except in compliance with the License. A copy of the License is located at
 *
 * http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and
 * limitations under the License.
 * *****************************************************************************
 *    __  _    _  ___
 *   (  )( \/\/ )/ __)
 *   /__\ \    / \__ \
 *  (_)(_) \/\/  (___/
 *
 *  AWS SDK for .NET
 *  API Version: 2009-11-30
 */

using System;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using System.Text;

using Amazon.Util;

namespace Amazon.EC2.Util
{
    /// <summary>
    /// This class represents S3 upload policy. Policy string
    /// representaion and signature to be used within EC2 bundling API.
    /// </summary>
    public class S3UploadPolicy
    {
        private string policySignature;
        private string policyString;
        private SecureString awsSecretAccessKey;

        /// <summary>
        /// S3 Upload policy to be used by EC2 API.
        /// </summary>
        /// <param name="awsAccessKeyId">Access Key Id of the signer of the policy</param>
        /// <param name="awsSecretAccessKey">Secret Key of the signer of the policy</param>
        /// <param name="bucketName">Bucket name to upload</param>
        /// <param name="prefix">Prefix for the object keys</param>
        /// <param name="expireInMinutes">Expire, minutes from now</param>
        ///
        public S3UploadPolicy(
                string awsAccessKeyId,
                System.Security.SecureString awsSecretAccessKey,
                string bucketName,
                string prefix,
                int expireInMinutes)
        {
          string policy = String.Concat(
              "{",
              "\"expiration\": \"",
              GetFormattedTimestamp(expireInMinutes),
              "\",",
              "\"conditions\": [",
              "{\"bucket\": \"",
              bucketName,
              "\"},",
              "{\"acl\": \"",
              "ec2-bundle-read",
              "\"},",
              "[\"starts-with\", \"$key\", \"",
              prefix,
              "\"]",
              "]}");
            this.policyString = Convert.ToBase64String(Encoding.UTF8.GetBytes(policy.ToCharArray()));
            this.awsSecretAccessKey = awsSecretAccessKey;
        }

        /// <summary>
        /// Base64 representation of the serialized policy.
        /// Use policy generated by this method
        /// for passing to EC2 bunding calls.
        /// </summary>
        /// <returns>Base64 policy</returns>
        public string PolicyString
        {
            get
            {
                return this.policyString;
            }
        }

        /// <summary>
        /// Policy signature in base64 format
        /// Use signature generated by this method
        /// for passing to EC2 bunding calls along with policy.
        /// </summary>
        /// <returns>Base64 signature</returns>
        public string PolicySignature
        {
            get
            {
                if (this.policySignature == null)
                {
                    this.policySignature = Sign(PolicyString, this.awsSecretAccessKey, new HMACSHA1());
                }
                return this.policySignature;
            }
        }

        /// <summary>
        /// Computes RFC 2104-compliant HMAC signature
        /// </summary>
        /// <param name="data">The data to be signed</param>
        /// <param name="key">The secret signing key</param>
        /// <param name="algorithm">The algorithm to sign the data with</param>
        /// <returns>A string representing the HMAC signature</returns>
        internal static string Sign(string data, System.Security.SecureString key, KeyedHashAlgorithm algorithm)
        {
            if (key == null)
            {
                throw new AmazonEC2Exception("The AWS Secret Access Key specified is NULL");
            }

            return AWSSDKUtils.HMACSign(data, key, algorithm);
        }

        internal static string GetFormattedTimestamp(int minutesFromNow)
        {
            DateTime dateTime = DateTime.Now.AddMinutes(minutesFromNow);
            return new DateTime(dateTime.Year,
                                dateTime.Month,
                                dateTime.Day,
                                dateTime.Hour,
                                dateTime.Minute,
                                dateTime.Second,
                                dateTime.Millisecond,
                                DateTimeKind.Local)
                               .ToUniversalTime()
                               .ToString("yyyy-MM-dd\\THH:mm:ss.fff\\Z",
                                CultureInfo.InvariantCulture);
        }
    }
}
