using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;


namespace P2MSampleApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //depending on the API used, these should be passed
            string httpMethod = "POST";//"GET"; 
            string endpointURL = "amazonpay-sandbox.amazon.in/v2/store"; //"/v1/smart-store/payment/charge/status";

            //should not be hardcoded and fetched from config. The value will depend on the merchant ID used.
            string secretKey = "3gY1vxWnx_L5bzguJLeZ-Mf3eYOsZxBlnYy6tWptDQMhk4fdW0hV0HwuE6QdipQ2";

            var paylod = P2MaddStore.P2MaddStoreParams();
            var headers = P2MaddStore.P2Mheaders();

            string stringToSign = P2MaddStore.StringToSign(paylod, headers, httpMethod,endpointURL);
            Console.WriteLine(stringToSign);

            string todayDate = DateTime.Now.ToString("yyyyMMdd");

            byte[] kSecret = Encoding.UTF8.GetBytes(("AWS4" + secretKey).ToCharArray());
            byte[] kDate = HmacSHA384(todayDate, kSecret);
            byte[] kRegion = HmacSHA384("eu-west-1", kDate);
            byte[] kService = HmacSHA384("AmazonPay", kRegion);
            byte[] kSigning = HmacSHA384("aws4_request", kService);

            byte[] hashedsignature = HmacSHA384(stringToSign, kSigning);
            string encodedsign = Convert.ToBase64String(hashedsignature);
            encodedsign = encodedsign.Split('=')[0];
            encodedsign = encodedsign.Replace('+', '-').Replace('/', '_');
            
            Console.WriteLine(value: "signature=" + encodedsign);

            //Adding signature to the request

            Console.ReadLine();

        }


         static byte[] HmacSHA384(String data, byte[] key)
        {
            String algorithm = "HmacSHA384";
            KeyedHashAlgorithm kha = KeyedHashAlgorithm.Create(algorithm);
            kha.Key = key;

            return kha.ComputeHash(Encoding.UTF8.GetBytes(data));
        }


        private static String encodeToUrlString(byte[] array)
        {

            string encodedpayload = Convert.ToBase64String(array);
            encodedpayload = encodedpayload.Split('=')[0];
            encodedpayload = encodedpayload.Replace('+', '-').Replace('/', '_');
            return encodedpayload;

        }
     

    }
}
