using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Vonage.Messaging;
using Vonage.Utility;


namespace VonageTest.Controllers
{
    public class ValuesController : ApiController
    {

        [System.Web.Http.HttpGet]
        [System.Web.Http.Route("api/sms/verify")]
        public IHttpActionResult VerifySms()
        {
            var vonageApiSignatureSecret = "";

            // Use Request.GetQueryNameValuePairs() (returns IEnumerable<KeyValuePair<string, string>>)
            var rawQuery = Request.GetQueryNameValuePairs();

            // Convert to IEnumerable<KeyValuePair<string, StringValues>>
            var queryParameters = rawQuery
                .GroupBy(kvp => kvp.Key)
                .Select(g => new KeyValuePair<string, StringValues>(g.Key, new StringValues(g.Select(x => x.Value).ToArray())))
                .ToList();

            // ParseQuery expects a NameValueCollection, which QueryString is
            var sms = WebhookParser.ParseQuery<InboundSms>(queryParameters);

            if (sms.ValidateSignature(vonageApiSignatureSecret, Vonage.Cryptography.SmsSignatureGenerator.Method.md5hash))
            {
                Console.WriteLine("Signature is valid");
            }
            else
            {
                Console.WriteLine("Signature not valid");
            }

            // Return HTTP 200 OK with empty content
            return Ok();
        }
    }
}
