using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Quadarax.Foundation.Core.Console;
using Quadarax.Foundation.Core.QConsole.Argument;
using Quadarax.Foundation.Core.QConsole.Attributes;
using Quadarax.Foundation.Core.QConsole.Command.Base;
using Quadarax.Foundation.Core.QConsole.Extensions;
using Quadarax.Foundation.Core.QConsole.Value;
using Quadarax.Foundation.Core.Value;

namespace Quadarax.Foundation.Core.QConsole.Command.Defaults
{
    [CommandDefinition]
    public class CmdHelp : AbstractCommand
    {
        #region *** Properties ***
        public override string Name => Constants.Commands.Help.Name;
        public override string Description => Constants.Commands.Help.Description;
        #endregion

        #region *** Constructors ***
        public CmdHelp(Engine engine) : base(engine)
        {
        }
        #endregion

        #region *** Protected overrides ***
        protected override Result OnExecute()
        {
            if (!GetArgument(Constants.Commands.Help.ArgCommandName.Code).Value.HasValue)
            {
                if (!Engine.Configuration.IsConsoleDebug)
                {
                    using (var writer = new ConsoleWriter(ConsoleColor.White))
                    {
                        writer.WriteLine(
                            "To enable debug mode - more verbosity - use argument \"-dbg\" at the end of line.");
                    }
                }

                using (var writer = new ConsoleWriter(ConsoleColor.Yellow))
                {
                    writer.WriteLine("Console commands list:");
                }

                using (var writer = new ConsoleWriter(ConsoleColor.Green))
                {
                    foreach (var command in Engine.Commands)
                    {
                        writer.WriteLine($"{command.Name}\t{command.Description}");
                    }

                    writer.WriteLine();
                }

                using (var writer = new ConsoleWriter(ConsoleColor.Yellow))
                {
                    writer.WriteLine($"To view more info for specific command type {Name} <{GetArgument(Constants.Commands.Help.ArgCommandName.Code).Hint}>");
                }


                if (GetArgumentValueOrDefault<bool>(Constants.Commands.Help.ArgFlagAll.Code))
                {
                    foreach (var command in Engine.Commands)
                    {
                        ShowCommandHelp(command);
                        WriteInfo("---");
                    }
                }

            }
        
            else
            {
                var argument = GetArgument(Constants.Commands.Help.ArgCommandName.Code);
                var command = Engine.GetCommand(argument.Value.AsString());
                if (command == null)
                    throw new Exception($"Unkonwn command '{argument.Value.AsString()}'");
                ShowCommandHelp(command);

            }
            return new Result();
        }

        protected override IEnumerable<AbstractArgument> OnSetupArguments()
        {
            var result = base.OnSetupArguments().ToList();
            result.AddRange( new AbstractArgument[]
            {
                new OrdinalArgument(0, true, 
                    Constants.Commands.Help.ArgCommandName.Code,
                    Constants.Commands.Help.ArgCommandName.Description,
                    Constants.Commands.Help.ArgCommandName.Hint,
                    TypeValuesEnum.String,
                    string.Empty,
                    false),
                new FlagArgument(Constants.Commands.Help.ArgFlagAll.Code,
                    Constants.Commands.Help.ArgFlagAll.Description,
                    Constants.Commands.Help.ArgFlagAll.Hint,
                    false
                    )
            });
            return result;
        }
        #endregion

        #region *** Private Operations ***

        private void ShowCommandHelp(AbstractCommand command)
        {
            using (var writer = new ConsoleWriter(ConsoleColor.Green))
            {
                using (var writerWhite = new ConsoleWriter(ConsoleColor.White))
                {
                    writer.Write($"Command: \t");
                    writerWhite.WriteLine(command.Name);
                    writer.Write($"Description: \t");
                    writerWhite.WriteLine(command.Description);
                    writer.Write($"Parameters: \t");
                    writerWhite.WriteLine((command.Arguments.Length == 0 ? "none" : string.Empty));
                    foreach (var arg in command.Arguments.OrderBy(x => x.IsPositional() ? 0 : 1))
                    {
                        var optional = arg.IsMandatory ? "Mandatory." : "Optional.";
                        var argumentName = arg.IsPositional()
                            ? $"<{arg.Code}>"
                            : $"{Engine.Configuration.CharacterNamedArgumentSeparator}{arg.Code}";
                        writer.WriteLine($"{argumentName}\t{optional}{arg.Description}");
                    }

                    var usage = new StringBuilder();
                    writer.WriteLine();
                    writer.WriteLine("Usage:");
                    writer.Write($"\t{Engine.Configuration.CharacterLineIntroduce}");
                    if (!string.IsNullOrEmpty(command.CustomUsage))
                    {
                        usage.Append(command.CustomUsage).AppendLine();
                    }
                    else
                    {
                        usage.Append(command.Name);
                        foreach (var arg in command.Arguments.OrderBy(x => x.IsPositional() ? 0 : 1))
                        {
                            usage.Append(" ");
                            usage.Append(GetArgumentEntryAsDescription(arg));
                        }
                    }

                    writerWhite.WriteLine(usage.ToString());

                    if (!string.IsNullOrEmpty(command.Notes))
                    {
                        writer.WriteLine();
                        writer.Write($"Notes: \t");
                        writer.Write($"\t{command.Notes}");
                    }

                    if (!string.IsNullOrEmpty(command.Examples))
                    {
                        writer.WriteLine();
                        writer.Write($"Examples: \t");
                        writer.Write($"\t{command.Examples}");
                    }
                }
            }
        }

        private string GetArgumentEntryAsDescription(AbstractArgument arg)
        {
            var argumentName = $"{Engine.Configuration.CharacterNamedArgumentSeparator}{arg.Code}";

            string argumentBody;
            if (arg.IsCodeAccessAllowed() && arg.IsPositional())
                argumentBody = "[" + argumentName + Engine.Configuration.CharacterNamedArgumentValueSeparator + "]" + arg.Hint;
            else if (arg.IsPositional())
                argumentBody = arg.Hint;
            else
                argumentBody = argumentName + Engine.Configuration.CharacterNamedArgumentValueSeparator + arg.Hint;

            if (!arg.IsMandatory)
            {
                argumentBody = "[" + argumentBody + "]";
            }

            return argumentBody;
        }
        #endregion
    }
}
