using System;
using System.Collections.Generic;
using Server;
using Server.Commands;
using Server.Mobiles;

namespace Server.Commands
{
    public class RetrieveMountCommand
    {
        public static void Initialize()
        {
            CommandSystem.Register("RetrieveMount", AccessLevel.Player, new CommandEventHandler(RetrieveMount_OnCommand));
        }

        [Usage("RetrieveMount")]
        [Description("Automatically retrieves your last stabled mount and remounts you upon exiting a restricted zone.")]
        public static void RetrieveMount_OnCommand(CommandEventArgs e)
        {
            PlayerMobile pm = e.Mobile as PlayerMobile;
            if (pm != null)
            {
                AutoRemountPlayer(pm);
            }
        }

        public static void AutoRemountPlayer(PlayerMobile pm)
        {
            if (pm == null || pm.Deleted)
                return;

            if (pm.Map == null || pm.Map == Map.Internal)
                return;

            if (pm.Mounted)
                return;

            BaseCreature mountToRetrieve = null;

            for (int i = pm.Stabled.Count - 1; i >= 0; i--)
            {
                BaseCreature pet = pm.Stabled[i] as BaseCreature;

                if (pet != null && pet is IMount && !pet.Deleted)
                {
                    mountToRetrieve = pet;
                    break; 
                }
            }

            if (mountToRetrieve != null)
            {
                pm.Stabled.Remove(mountToRetrieve);
                mountToRetrieve.SetControlMaster(pm);
                mountToRetrieve.IsStabled = false;
                mountToRetrieve.MoveToWorld(pm.Location, pm.Map);
                IMount mount = mountToRetrieve as IMount;
                if (mount != null)
                {
                    mount.Rider = pm; 
                    //pm.SendMessage("Welcome back! Your mount has been returned to you.");
                }
            }
        }
    }
}
