using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Aspects;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace WorkerRole
{
    [AverageTimePerformanceCounterAspect(AttributeExclude = true)]
    public class PerformanceCountersAspectsSettingsManager : IPerformanceCountersAspectsSettingsManager
    {
        public PerformanceCountersAspectsSettingsManager()
        {
            RoleEnvironment.Changing += (sender, args) =>
            {
                Trace.TraceInformation("Configuration changing!");
                args.Cancel = false; //do not restart the role 
            };

            RoleEnvironment.Changed += (sender, args) =>
            {

                Trace.TraceInformation("Configuration changed!");
                var changes = args.Changes.OfType<RoleEnvironmentConfigurationSettingChange>();

                foreach (RoleEnvironmentConfigurationSettingChange change in changes)
                {
                    Trace.TraceInformation("Configuration entry '{0}' changed", change.ConfigurationSettingName);
                }

                WriteOutCurrentConfigurationEntryValue("MembersToMeasured", CloudConfigurationManager.GetSetting("MembersToBeMeasured"));

                OnConfigurationChanged();
            };

        }

        public event EventHandler ConfigurationChanged;

        public IEnumerable<string> MembersToMeasured
        {
            get { return CloudConfigurationManager.GetSetting("MembersToBeMeasured").Split(';'); }
        }

        protected virtual void OnConfigurationChanged()
        {
            EventHandler handler = ConfigurationChanged;
            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }

        private void WriteOutCurrentConfigurationEntryValue(string name, string value)
        {
            Trace.TraceInformation("The configuration entry '{0}' has value(s) '{1}'", name, value);
        }
    }
}