using System;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading;
using System.Xml.Serialization;
using Microsoft.Samples.ServiceHosting.StorageClient;
using Microsoft.ServiceHosting.ServiceRuntime;
using ReminderService_WebRole;

namespace ReminderService_WorkerRole
{
public class WorkerRole : RoleEntryPoint
{
    public override void Start()
    {
         while (true)
        {
            Thread.Sleep(100);
            RoleManager.WriteToLog("Information", "Working");

            //Lese Nachricht aus Queue
            QueueStorage qs = QueueStorage.Create(StorageAccountInfo
                .GetDefaultQueueStorageAccountFromConfiguration());
            MessageQueue mq = qs.GetQueue("termine");
            mq.CreateQueue();
            Message message = mq.GetMessage(10);
            if (message != null)
            {
                //Deserialisieren des Termins
                XmlSerializer xs = new XmlSerializer(typeof(Termin));
                MemoryStream ms = new MemoryStream(Encoding
                    .ASCII.GetBytes(message.ContentAsString()));
                Termin termin = (Termin)xs.Deserialize(ms);

                //Prüfen ob bereits im Table Storage vorhanden
                TerminContext context = 
                    new TerminContext(StorageAccountInfo
                    .GetDefaultTableStorageAccountFromConfiguration());
                var results = (from g in context.Termin
                               where g.RowKey.Equals(termin.RowKey)
                               select g).ToList();
                //Wenn nein    
                if (results.Count == 0)
                {
                    //In Table speichern
                    context.AddObject("Termin", termin);
                    context.SaveChanges();

                    //Mail-Versand
                    sendMail(termin.Beschreibung);
                }
                //Nachricht aus Queue löschen
                mq.DeleteMessage(message);
            }
        }
    }
    public static void sendMail(string eMailBody)
    {
        try
        {
            MailMessage mail = new MailMessage();
            MailAddress from = new MailAddress("xxx@xxx.de");
            mail.To.Add("xxx@xxx.de");
            mail.From = new MailAddress("xxx@xxx.de");
            mail.Subject = "Neuer Eintrag im Online-Kalender";
            mail.Body = eMailBody;
            SmtpClient client = new SmtpClient("smtp.xxx.de",25);
            client.Credentials = new System.Net
                .NetworkCredential("xxx", "xxx");
            client.Send(mail);
        }
        catch (Exception e)
        {
            RoleManager.WriteToLog("Error", e.Message);
        }
    }
    public override RoleStatus GetHealthStatus()
    {
        return RoleStatus.Healthy;
    }
}
}
