using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.WindowsAzure;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;

namespace Univ.Controllers
{
    public class HomeController : Controller
    {
        string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
        string qname = "signups";

        public ActionResult Index()
        {
            ViewBag.Message = "Newsletter Signups";
            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        [HttpPost]
        public ActionResult Newsletter(string email)
        {
            var nm = NamespaceManager.CreateFromConnectionString(connectionString);
            QueueDescription qd = new QueueDescription(qname);
            qd.MaxSizeInMegabytes = 2048;  //Max size of queue is 2GB
            qd.DefaultMessageTimeToLive = new TimeSpan(0, 5, 0); //Max TTL is 5 minutes

            if (!nm.QueueExists(qname))
            {
                nm.CreateQueue(qd);
            }

            //Send to the Queue
            QueueClient qc = QueueClient.CreateFromConnectionString(connectionString, qname);

            //Create msg with email property and send to QueueClient
            var bm = new BrokeredMessage();
            bm.Properties["email"] = email;
            qc.Send(bm);
            
            ViewBag.email = email;

            return View();
        }
    }
}
