/**
  	  * Constructor with arguments
  	  */
 public ConvertCurrencyRequest(RequestEnvelope requestEnvelope, CurrencyList baseAmountList, CurrencyCodeList convertToCurrencyList)
 {
     this.requestEnvelope = requestEnvelope;
     this.baseAmountList = baseAmountList;
     this.convertToCurrencyList = convertToCurrencyList;
 }
        /// <summary>
        /// Handle ConvertCurrency API call
        /// </summary>
        /// <param name="context"></param>
        private void ConvertCurrency(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            string[] fromCurrencyCodes = context.Request.Form.GetValues("currencyCode");
            string[] fromCurrencyAmounts = context.Request.Form.GetValues("currencyAmount");
            string[] toCurrencyCodes = context.Request.Form.GetValues("toCurrencyCode");

            List<CurrencyType> currencies = new List<CurrencyType>();
            for(int i=0; i<fromCurrencyCodes.Length; i++)
            {
                currencies.Add(
                    new CurrencyType(fromCurrencyCodes[i], decimal.Parse(fromCurrencyAmounts[i]))
                );
            }
            CurrencyList baseAmountList = new CurrencyList(currencies);

            List<String> toCurrencyCodeList = new List<String>();
            for (int i = 0; i < toCurrencyCodes.Length; i++)
                toCurrencyCodeList.Add(toCurrencyCodes[i]);
            CurrencyCodeList convertToCurrencyList = new CurrencyCodeList(toCurrencyCodeList);

            ConvertCurrencyRequest req = new ConvertCurrencyRequest(
                new RequestEnvelope("en_US"), baseAmountList, convertToCurrencyList);
            // Add optional parameters
            if (parameters["countryCode"] != "")
                req.countryCode = parameters["countryCode"];
            if (parameters["conversionType"] != "")
                req.conversionType = parameters["conversionType"];

            // All set. Fire the request
            AdaptivePaymentsService service = new AdaptivePaymentsService();
            ConvertCurrencyResponse resp = null;
            try
            {
                resp = service.ConvertCurrency(req);
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
                return;
            }

            // Display response values.
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(resp.responseEnvelope.ack == AckCode.FAILURE) &&
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                if (resp.estimatedAmountTable != null
                    && resp.estimatedAmountTable.currencyConversionList != null)
                {
                    int idx = 1;
                    foreach (CurrencyConversionList list in resp.estimatedAmountTable.currencyConversionList)
                    {
                        keyResponseParams.Add("Base amount " + idx,
                            list.baseAmount.amount + " " + list.baseAmount.code);
                        idx++;
                    }
                }

                //Selenium Test Case
                keyResponseParams.Add("Acknowledgement", resp.responseEnvelope.ack.ToString());
            }
            displayResponse(context, "ConvertCurrency", keyResponseParams, service.getLastRequest(), service.getLastResponse(),
                resp.error, redirectUrl);
        }
    // # ConvertCurrency API Operation  
    // The ConvertCurrency API operation to request the current foreign exchange (FX) rate for a specific amount and currency      
    public ConvertCurrencyResponse ConvertCurrencyAPIOperation()
    {
        // Create the ConvertCurrencyResponse object
        ConvertCurrencyResponse responseConvertCurrency = new ConvertCurrencyResponse();

        try
        {
            // # ConvertCurrencyRequest 
            // The ConvertCurrencyRequest message enables you to have your  
            // application get an estimated exchange rate for a list of amounts 
            // This API operation does not affect PayPal balances   
            // The code for the language in which errors are returned
            RequestEnvelope envelopeRequest = new RequestEnvelope();
            envelopeRequest.errorLanguage = "en_US";

            // CurrencyTypeList which takes two arguments:  
            //  
            // * `CurrencyCodeType` - The currency code. Allowable values are:  
            // * Australian Dollar - AUD    
            // * Brazilian Real - BRL   
            // `Note:   
            // The Real is supported as a payment currency and currency balance only for Brazilian PayPal accounts.`  
            //  
            // * Canadian Dollar - CAD  
            // * Czech Koruna - CZK 
            // * Danish Krone - DKK 
            // * Euro - EUR 
            // * Hong Kong Dollar - HKD 
            // * Hungarian Forint - HUF 
            // * Israeli New Sheqel - ILS   
            // * Japanese Yen - JPY 
            // * Malaysian Ringgit - MYR    
            // `Note:   
            // The Ringgit is supported as a payment currency and currency balance only for Malaysian PayPal accounts.`
            //  
            // * Mexican Peso - MXN 
            // * Norwegian Krone - NOK  
            // * New Zealand Dollar - NZD   
            // * Philippine Peso - PHP  
            // * Polish Zloty - PLN 
            // * Pound Sterling - GBP   
            // * Singapore Dollar - SGD 
            // * Swedish Krona - SEK    
            // * Swiss Franc - CHF  
            // * Taiwan New Dollar - TWD    
            // * Thai Baht - THB    
            // * Turkish Lira - TRY 
            // `Note:   
            // The Turkish Lira is supported as a payment currency and currency balance only for Turkish PayPal accounts.`
            //  
            // * U.S. Dollar - USD  
            // * `amount`   
            List<CurrencyType> currencyTypeList = new List<CurrencyType>();
            CurrencyType currency = new CurrencyType("USD", Convert.ToDecimal("4.00"));
            currencyTypeList.Add(currency);
            CurrencyList baseAmountList = new CurrencyList(currencyTypeList);

            // CurrencyCodeList which contains  
            //  
            // * `Currency Code` - Allowable values are:    
            // * Australian Dollar - AUD    
            // * Brazilian Real - BRL   
            // `Note:   
            // The Real is supported as a payment currency and currency balance only for Brazilian PayPal accounts.`  
            // * Canadian Dollar - CAD  
            // * Czech Koruna - CZK 
            // * Danish Krone - DKK 
            // * Euro - EUR 
            // * Hong Kong Dollar - HKD 
            // * Hungarian Forint - HUF 
            // * Israeli New Sheqel - ILS   
            // * Japanese Yen - JPY 
            // * Malaysian Ringgit - MYR    
            // `Note:   
            // The Ringgit is supported as a payment currency and currency balance  only for Malaysian PayPal accounts.` 
            // * Mexican Peso - MXN 
            // * Norwegian Krone - NOK  
            // * New Zealand Dollar - NZD   
            // * Philippine Peso - PHP  
            // * Polish Zloty - PLN 
            // * Pound Sterling - GBP   
            // * Singapore Dollar - SGD 
            // * Swedish Krona - SEK    
            // * Swiss Franc - CHF  
            // * Taiwan New Dollar - TWD    
            // * Thai Baht - THB    
            // * Turkish Lira - TRY 
            // `Note:   
            // The Turkish Lira is supported as a payment currency and currency balance only for Turkish PayPal accounts.`   
            //  
            // * U.S. Dollar - USD  
            List<String> currencyCodeList = new List<String>();
            currencyCodeList.Add("GBP");
            CurrencyCodeList convertToCurrencyList = new CurrencyCodeList(currencyCodeList);

            // ConvertCurrencyRequest which takes params:   
            //
            // * `Request Envelope` - Information common to each API operation, such    
            // as the language in which an error message is returned    
            // * `BaseAmountList` - A list of amounts with associated currencies to 
            // be converted.    
            // * `ConvertToCurrencyList` - A list of currencies to convert to.  
            ConvertCurrencyRequest requestConvertCurrency = new ConvertCurrencyRequest(envelopeRequest, baseAmountList, convertToCurrencyList);
            
            // # Create the service wrapper object to make the API call   
            AdaptivePaymentsService service = new AdaptivePaymentsService();

            // # API call   
            // Invoke the ConvertCurrency method in service wrapper object  
            responseConvertCurrency = service.ConvertCurrency(requestConvertCurrency);

            if (responseConvertCurrency != null)
            {
                // Response envelope acknowledgement
                string acknowledgement = "ConvertCurrency API operation - ";
                acknowledgement += responseConvertCurrency.responseEnvelope.ack.ToString();
                logger.Info(acknowledgement + "\n");
                Console.WriteLine(acknowledgement + "\n");
 
                // # Success values   
                if (responseConvertCurrency.responseEnvelope.ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    if (responseConvertCurrency.estimatedAmountTable.currencyConversionList != null
                        && responseConvertCurrency.estimatedAmountTable.currencyConversionList.Count > 0)
                    {
                        IEnumerator<CurrencyConversionList> iterator = responseConvertCurrency.estimatedAmountTable.currencyConversionList.GetEnumerator();

                        while (iterator.MoveNext())
                        {
                            CurrencyConversionList currencyConversion = iterator.Current;
                            logger.Info("Amount to be Converted : " + currencyConversion.baseAmount.amount + currencyConversion.baseAmount.code + "\n");
                            Console.WriteLine("Amount to be Converted : " + currencyConversion.baseAmount.amount + currencyConversion.baseAmount.code + "\n");

                            IEnumerator<CurrencyType> currencyIterator = currencyConversion.currencyList.currency.GetEnumerator();

                            while (currencyIterator.MoveNext())
                            {
                                CurrencyType currencyType = currencyIterator.Current;
                                logger.Info("Converted amount : " + currencyType.amount + currencyType.code + "\n");
                                Console.WriteLine("Converted amount : " + currencyType.amount + currencyType.code + "\n");
                            }
                        }
                    }
                }
                // # Error Values 
                else
                {
                    List<ErrorData> errorMessages = responseConvertCurrency.error;
                    foreach (ErrorData error in errorMessages)
                    {
                        logger.Debug("API Error Message : " + error.message);
                        Console.WriteLine("API Error Message : " + error.message + "\n");
                    }
                }
            }
        }
        // # Exception log    
        catch (System.Exception ex)
        {
            // Log the exception message       
            logger.Debug("Error Message : " + ex.Message);
            Console.WriteLine("Error Message : " + ex.Message);
        }

        return responseConvertCurrency;
    }
        /// <summary>
        /// Handle ConvertCurrency API call
        /// </summary>
        /// <param name="contextHttp"></param>
        private void ConvertCurrency(HttpContext contextHttp)
        {
            NameValueCollection parameters = contextHttp.Request.Params;
            // (Required) The currency code
            string[] fromCurrencyCodes = contextHttp.Request.Form.GetValues("currencyCode");

            //(Required) The amount to be converted.
            string[] fromCurrencyAmounts = contextHttp.Request.Form.GetValues("currencyAmount");

            // (Required) The currency code
            string[] toCurrencyCodes = contextHttp.Request.Form.GetValues("toCurrencyCode");

            List<CurrencyType> currencies = new List<CurrencyType>();
            for(int i=0; i<fromCurrencyCodes.Length; i++)
            {
                currencies.Add(
                    new CurrencyType(fromCurrencyCodes[i], Convert.ToDecimal(fromCurrencyAmounts[i]))
                );
            }
            CurrencyList baseAmountList = new CurrencyList(currencies);

            List<string> toCurrencyCodeList = new List<string>();
            for (int i = 0; i < toCurrencyCodes.Length; i++)
                toCurrencyCodeList.Add(toCurrencyCodes[i]);
            CurrencyCodeList convertToCurrencyList = new CurrencyCodeList(toCurrencyCodeList);

            ConvertCurrencyRequest request = new ConvertCurrencyRequest(
                new RequestEnvelope("en_US"), baseAmountList, convertToCurrencyList);
            
            // (Optional)The two-character ISO code for the country where the
		    // function is supposed to happen. The default value is US.
            if (parameters["countryCode"] != string.Empty)
                request.countryCode = parameters["countryCode"];

            // (Optional)The conversion type allows you to determine the converted amounts 
            // for a PayPal user in different currency conversion scenarios, e.g., 
            // sending a payment in a different currency than what this user holds, 
            // accepting payment in a different currency than what the user holds, 
            // or converting a balance to a different currency than the user holds.. 
            // The default value is SENDER_SIDE .
            if (parameters["conversionType"] != string.Empty)
                request.conversionType = parameters["conversionType"];

            AdaptivePaymentsService service = null;
            ConvertCurrencyResponse response = null;
            try
            {
                // Configuration map containing signature credentials and other required configuration.
                // For a full list of configuration parameters refer in wiki page 
                // (https://github.com/paypal/sdk-core-dotnet/wiki/SDK-Configuration-Parameters)
                Dictionary<string, string> configurationMap = Configuration.GetAcctAndConfig();

                // Creating service wrapper object to make an API call and loading
                // configuration map for your credentials and endpoint
                service = new AdaptivePaymentsService(configurationMap);
                response = service.ConvertCurrency(request);
            }
            catch (System.Exception e)
            {
                contextHttp.Response.Write(e.Message);
                return;
            }

            Dictionary<string, string> responseValues = new Dictionary<string, string>();
            string redirectUrl = null;
            if (!(response.responseEnvelope.ack == AckCode.FAILURE) &&
                !(response.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                if (response.estimatedAmountTable != null
                    && response.estimatedAmountTable.currencyConversionList != null)
                {
                    int idx = 1;

                    //The list of converted currencies.
                    foreach (CurrencyConversionList list in response.estimatedAmountTable.currencyConversionList)
                    {
                        responseValues.Add("Base amount " + idx,
                            list.baseAmount.amount + " " + list.baseAmount.code);
                        idx++;
                    }
                }

                
                responseValues.Add("Acknowledgement", response.responseEnvelope.ack.ToString());
            }
            Display(contextHttp, "ConvertCurrency", responseValues, service.getLastRequest(), service.getLastResponse(), response.error, redirectUrl);
        }