﻿using System;

namespace EmailRegistry_3_5.Infrastructure.Extensions.Commands
{
    public class CommandState : ICommandState
    {
        public bool WasStarted { get; private set; }

        private bool _isCompleted;
        public bool IsCompleted
        {
            get => _isCompleted;
            private set
            {
                if (!WasStarted)
                {
                    throw new InvalidOperationException("Command was not triggered to start.");
                }

                _isCompleted = value;
            }
        }

        private bool _wasFailed;
        public bool WasFailed
        {
            get => _wasFailed;
            private set
            {
                CheckIfCommandWasCompleted();
                _wasFailed = value;
            }
        }

        private bool _wasSuccessfull;
        public bool WasSuccessfull
        {
            get => _wasSuccessfull;
            private set
            {
                CheckIfCommandWasCompleted();
                _wasSuccessfull = value;
            }
        }

        public void StartExecution()
        {
            if (WasStarted)
            {
                throw new InvalidOperationException("Execution was started already.");
            }

            WasStarted = true;
        }

        // TODO seems to be there is a sense to hold exception here
        public void CompleteExecution(bool success)
        {
            IsCompleted = true;
            WasFailed = !success;
            WasSuccessfull = success;
        }

        private void CheckIfCommandWasCompleted()
        {
            if (!IsCompleted)
            {
                throw new InvalidOperationException("Command is not finished yet.");
            }
        }
    }
}