using System;
using System.Collections.Generic;
using McBits.ThreadSafeRandom;

namespace GrizzenServer
{
    public class HealCmd : Cmd
    {
        public HealCmd(Client client) : base(client) { }
        public HealCmd(string scene, string actor, IList<string> args) : base(scene, actor, args) { }

        public override TimeSpan Timeout { get; } = TimeSpan.FromSeconds(1.5);

        protected override int EnergyCost { get; } = 5;

        public override void Run()
        {
            if (HasAccess
                && MinArgs(1))
            {
                string target = Args[0];

                if (!Db.BodyExists(target) ||
                Db.SceneByBody(Actor) != Db.SceneByBody(target) ||
                Db.Health(target) <= 0)
                    Error(Actor, ErrorCode.InvalidTarget);
                else if (Db.Energy(Actor) <= EnergyCost)
                    Error(Actor, ErrorCode.NotEnoughEnergy);
                else
                {
                    var boost = Math.Min(SafeRandom.Next(50) + 1, 100 - Db.Health(target));

                    // Set new health
                    int newHealth = Math.Max(0, Math.Min(100, Db.Health(target) + boost));
                    Db.Health(target, newHealth);

                    // Set new energy
                    int newEnergy = Math.Max(0, Math.Min(100, Db.Energy(Actor) - EnergyCost));
                    Db.Energy(Actor, newEnergy);

                    // Notify
                    Clients.TellBody(target, "Health", newHealth.ToString());
                    Clients.TellBody(Actor, "Energy", newEnergy.ToString());
                    Clients.TellScene(Scene, "Heal", Actor, target);
                }
            }
        }
    }
}
