using System;
using System.Collections.Generic;
using Server;
using Server.Engines.Craft;
using Server.Items;

namespace Server.Engines.Craft
{
    public class CraftQueueEntry
    {
        public CraftItem CraftItem { get; set; }
        public Type ResourceType { get; set; }
        public int TargetAmount { get; set; }
        public int AmountMade { get; set; }
        public int AmountFailed { get; set; }
        public int AmountExceptional { get; set; }
        public bool IsCompleted { get; set; }

        public CraftQueueEntry( CraftItem item, Type resType, int target )
        {
            CraftItem = item;
            ResourceType = resType;
            TargetAmount = target;
            IsCompleted = false;
        }
    }

    public class CraftQueue
    {
        public List<CraftQueueEntry> Entries { get; set; }
        public bool IsPaused { get; set; }

        public CraftQueue()
        {
            Entries = new List<CraftQueueEntry>();
            IsPaused = true; // Always start paused so they can safely build the list
        }
    }

    public static class CraftQueueManager
    {
        private static Dictionary<Mobile, Dictionary<CraftSystem, CraftQueue>> m_Data = new Dictionary<Mobile, Dictionary<CraftSystem, CraftQueue>>();

        // Here is the GetQueue method that went missing!
        public static CraftQueue GetQueue( Mobile m, CraftSystem system )
        {
            if ( !m_Data.ContainsKey( m ) )
                m_Data[m] = new Dictionary<CraftSystem, CraftQueue>();

            if ( !m_Data[m].ContainsKey( system ) )
                m_Data[m][system] = new CraftQueue();

            return m_Data[m][system];
        }

        public static bool CheckQueue( Mobile from, CraftSystem system, BaseTool tool, int endquality, bool success, object haltMessage )
        {
            CraftQueue queue = GetQueue( from, system );
    
            if ( queue.IsPaused || queue.Entries.Count == 0 )
                return false;

            // --- AVATARS CONQUEST: Seamless Auto-Tool Replacement ---
            if ( haltMessage is int && (int)haltMessage == 1044038 )
            {
                BaseTool replacement = from.Backpack != null ? from.Backpack.FindItemByType( tool.GetType() ) as BaseTool : null;
        
                if ( replacement != null && !replacement.Deleted && replacement.UsesRemaining > 0 )
                {
                    tool = replacement; // Swap to the new tool
                    haltMessage = null; // Erase the error message so the queue doesn't pause!
                    from.SendMessage( 0x35, "Your tool broke, but you automatically equipped a new one!" );
                }
            }

            // 1. Tally stats for the item that just finished
            CraftQueueEntry current = queue.Entries.Find( e => !e.IsCompleted );
            
            if ( current != null )
            {
                if ( success )
                {
                    current.AmountMade++; // <--- The ONLY place it counts up now!
            
                    if ( endquality == 2 )
                        current.AmountExceptional++;

                    if ( current.AmountMade >= current.TargetAmount )
                    {
                        current.IsCompleted = true;
                        from.SendMessage( 0x3E, "Queue task complete: " + current.CraftItem.NameString );
                    }
                }
                else
                {
                    // If it wasn't a success and it isn't just a broken tool, count it as a failure
                    if ( haltMessage is int && (int)haltMessage == 1044038 )
                    {
                        // The item WAS successfully made, the tool just broke, so don't count a failure
                    }
                    else
                    {
                        current.AmountFailed++;
                        
                        // Also check completion on failure if we want to stop after X attempts
                        if ( (current.AmountMade + current.AmountFailed) >= current.TargetAmount )
                        {
                            current.IsCompleted = true;
                            from.SendMessage( 0x3E, "Queue task complete (with failures): " + current.CraftItem.NameString );
                        }
                    }
                }
            }

            if ( haltMessage != null )
            {
                queue.IsPaused = true;
                from.SendMessage( 0x22, "Queue paused: Missing materials, tool broke, or skill too low." );
                from.CloseGump( typeof( CraftQueueGump ) );
                from.SendGump( new CraftQueueGump( from, system, tool ) );
                return false;
            }

            // Refresh UI
            from.CloseGump( typeof( CraftQueueGump ) );
            from.SendGump( new CraftQueueGump( from, system, tool ) );

            // 2. Logic to find the NEXT thing to craft
            Timer.DelayCall( TimeSpan.FromSeconds( 1.0 ), delegate()
            {
                CraftQueue currentQueue = GetQueue( from, system );
        
                // Find the next incomplete item
                CraftQueueEntry next = currentQueue.Entries.Find( e => !e.IsCompleted );
        
                if ( !currentQueue.IsPaused && next != null && from.NetState != null && tool != null && !tool.Deleted )
                {
                    // Execute the craft call for the NEXT item
                    next.CraftItem.Craft( from, system, next.ResourceType, tool );
                }
                else if ( next == null ) // All entries completed
                {
                    currentQueue.IsPaused = true;
                    from.SendMessage( 0x3E, "All crafting queue tasks are finished." );
                    from.CloseGump( typeof( CraftQueueGump ) );
                    from.SendGump( new CraftQueueGump( from, system, tool ) );
                }
            });
            
            return true;
        }
    }
}
