using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
//using Microsoft.WindowsAzure.Storage;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;
using Microsoft.WindowsAzure.StorageClient;
 
namespace SignupsWorker
{
    public class WorkerRole : RoleEntryPoint
    {
        string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
        string qname = "signups";
        string tableConnectionString = CloudConfigurationManager.GetSetting("TableStorageConnection");


        public override void Run()
        {
            // This is a sample worker implementation. Replace with your logic.
            Trace.TraceInformation("SignupsWorker entry point called", "Information");

            while (true)
            {
                QueueClient qc = QueueClient.CreateFromConnectionString(connectionString, qname);
                BrokeredMessage msg = qc.Receive();

                if (msg != null)
                {
                    try
                    {
                        Trace.WriteLine("New Signup processed: " + msg.Properties["email"]);
                        msg.Complete();

                        //Log to Table Storage
                        SaveToStorage(msg.Properties["email"].ToString());

                    }
                    catch (Exception)
                    {
                        // Indicate a problem, unlock message in queue
                        msg.Abandon();
                    }
                }
            }
        }

        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections 
            ServicePointManager.DefaultConnectionLimit = 12;

            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            return base.OnStart();
        }

        private void SaveToStorage(string email)
        {
            string tableName = "signups";
            //Connection to Table Storage
            CloudStorageAccount account = CloudStorageAccount.Parse(tableConnectionString);

            //Client for Table Storage
            CloudTableClient tableStorage = account.CreateCloudTableClient();

            tableStorage.CreateTableIfNotExist(tableName);

            //Create new perosn object and set email
            TableServiceContext context = tableStorage.GetDataServiceContext();
            PersonEntity person = new PersonEntity();
            person.Email = email;
            person.PartitionKey = "newsletter";
            person.RowKey = email;

            //Save new person out to signups table
            context.AddObject(tableName, person);
            context.SaveChanges();


        }
    }
}
