using MainShell.Log;
using MainShell.ProcessResult;
using System;
using MW.WorkFlow;

namespace MainShell.Process
{
    public class WorkflowRuntimeTracker : IWorkflowRuntimeTracker
    {
        private readonly ProcessResultManager _processResultManager;

        public WorkflowRuntimeTracker(ProcessResultManager processResultManager)
        {
            _processResultManager = processResultManager ?? throw new ArgumentNullException(nameof(processResultManager));
        }

        public void UpdateExecutionPointer(WorkflowExecutionPointer executionPointer)
        {
            if (executionPointer != null)
            {
                string.Format(
                    "Workflow pointer updated. WorkflowName={0}, FlowName={1}, ActivityName={2}, CurrentStepId={3}, NextStepId={4}, UpdatedAt={5:yyyy-MM-dd HH:mm:ss.fff}.",
                    NormalizeValue(executionPointer.WorkflowName),
                    NormalizeValue(executionPointer.FlowName),
                    NormalizeValue(executionPointer.ActivityName),
                    NormalizeValue(executionPointer.CurrentStepId),
                    NormalizeValue(executionPointer.NextStepId),
                    executionPointer.UpdatedAt).LogProcessDebug();
            }

            _processResultManager.UpdateExecutionPointer(executionPointer);
        }

        public void ReportWorkflowFault(WorkflowFaultInfo faultInfo)
        {
            if (faultInfo != null)
            {
                string.Format(
                    "Workflow fault reported. WorkflowName={0}, FlowName={1}, ActivityName={2}, CurrentStepId={3}, OccurredAt={4:yyyy-MM-dd HH:mm:ss.fff}, ErrorMessage={5}.",
                    NormalizeValue(faultInfo.WorkflowName),
                    NormalizeValue(faultInfo.FlowName),
                    NormalizeValue(faultInfo.ActivityName),
                    NormalizeValue(faultInfo.CurrentStepId),
                    faultInfo.OccurredAt,
                    NormalizeValue(faultInfo.ErrorMessage)).LogProcessError();
            }

            _processResultManager.ReportWorkflowFault(faultInfo);
        }

        private static string NormalizeValue(string value)
        {
            return string.IsNullOrWhiteSpace(value) ? "N/A" : value;
        }
    }
}
