using System;
using System.Activities.Tracking;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activities;
using System.ServiceModel.Activities.Tracking.Configuration;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Web;
using System.Web.Configuration;

namespace SignalRWorkflowTracking
{
    public class SignalRTrackingBehavior : IServiceBehavior
    {

        private string _profile = string.Empty;
        private string _busName = string.Empty;

        public SignalRTrackingBehavior(string profileName, string busName)
        {
            _profile = profileName;
            _busName = busName;
        }

        private TrackingProfile GetProfile(string profileName)
        {
            TrackingProfile trackingProfile = null;
            TrackingSection trackingSection = (TrackingSection)WebConfigurationManager.GetSection("system.serviceModel/tracking");
            if (trackingSection == null)
            {
                return null;
            }

            if (profileName == null)
            {
                profileName = "";
            }

            //Find the profile with the specified profile name in the list of profile found in config
            var match = from p in new List<TrackingProfile>(trackingSection.TrackingProfiles)
                        where (p.Name == profileName)
                        select p;

            trackingProfile = match.SingleOrDefault();
            
            return trackingProfile;
        }
        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            WorkflowServiceHost serviceHost = serviceHostBase as WorkflowServiceHost;
            TrackingProfile profile = GetProfile(_profile);
            if (profile == null)
                profile = GetProfile("HealthMonitoring Profile");

            if (serviceHost == null)
            {
                return;
            }

            serviceHost.WorkflowExtensions.Add(() => new SignalRTrackingParticipant(_busName)
                {TrackingProfile = profile, BusURL = _busName});

        }

        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase){}

        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters){}

    }
}