using System;
using System.Activities.Tracking;
using System.Threading.Tasks;
using Newtonsoft.Json;
using SignalR.Client;

namespace SignalRWorkflowTracking
{
    public class SignalRTrackingParticipant : TrackingParticipant
    {
        private static Connection connection;
        private string _busURL = string.Empty;

        public SignalRTrackingParticipant(string busURL)
        {
            _busURL = busURL;
            if (connection == null)
            {
                connection = new Connection(BusURL);
                connection.Start().ContinueWith(task =>
                    {
                        if (task.IsFaulted)
                        {
                            Console.WriteLine("Failed to start: {0}", task.Exception.GetBaseException());
                        }
                        else
                        {
                            Console.WriteLine("Success! Connected with client connection id {0}",
                                              connection.ConnectionId);
                            // Do more stuff here
                        }
                    }).Wait();
                connection.Send("signalr tracking started");
            }
            
        }

        public string BusURL
        {
            get { return _busURL; }
            set { _busURL = value; }
        }



        protected override void Track(TrackingRecord record, TimeSpan timeout)
        {
            ActivityStateRecord activity = record as ActivityStateRecord;
            ActivityScheduledRecord activitySchedule = record as ActivityScheduledRecord;
            WorkflowInstanceRecord workflow = record as WorkflowInstanceRecord;
            Task t = null;
            if (activity != null)
            {
               
                //var recordData = new {TheType = "Activity", Data = data, ActivityName = activity.Activity.Name, Time = record.EventTime};
                //var recordData = new { TheType = "Activity", InstanceId = activity.InstanceId, ActivityId = activity.Activity.Id, Data = activity.Arguments, Meta = activity.Annotations, ActivityName = activity.Activity.Name, Time = record.EventTime };
                string sData = JsonConvert.SerializeObject(record, Formatting.Indented,
                    new JsonSerializerSettings()
                    {
                        ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                    });
                t = connection.Send(sData);
            }

            if (activitySchedule  != null)
            {
                var recordData = new { TheType = "Schedule", InstanceId = activitySchedule.InstanceId, ActivityId = activitySchedule.Activity.Id, Data = activitySchedule.Child.Name, Time = record.EventTime };
                t = connection.Send(record);
            }
            if (workflow != null)
            {
                var recordData =
                    new { TheType = "Workflow", InstanceId = workflow.InstanceId, Name = workflow.ActivityDefinitionId, State = workflow.State.ToString(), Time = record.EventTime };
                connection.Send(record);
            }

            if (t != null)
            {
                t.ContinueWith(task =>
                    {
                        if (t.IsFaulted)
                        {
                            //need to log here somewhere
                        }
                        else
                        {
                            Console.WriteLine("Success");
                        }
                    });
            }

        }


    }
}