using System;
using Server.Gumps;
using Server.Network;
using Server.Mobiles;
using Server.Items;

namespace Server.Engines.Craft
{
	public class CraftQueueGump : Gump
	{
		private Mobile m_From;
		private CraftSystem m_System;
		private BaseTool m_Tool;
		private CraftQueue m_Queue;

		public CraftQueueGump( Mobile from, CraftSystem system, BaseTool tool ) : base( 40, 40 )
		{
			m_From = from;
			m_System = system;
			m_Tool = tool;
			m_Queue = CraftQueueManager.GetQueue( from, system );

			AddPage( 0 );
			AddBackground( 0, 0, 600, 440, 5054 );
			AddImageTiled( 10, 10, 580, 22, 2624 );
			AddImageTiled( 10, 37, 580, 360, 2624 );
			AddImageTiled( 10, 402, 580, 28, 2624 );
			AddAlphaRegion( 10, 10, 580, 420 );

			AddHtml( 10, 12, 580, 20, "<CENTER><BASEFONT COLOR=#FFFFFF>CRAFTING QUEUE</BASEFONT></CENTER>", false, false );

			// Column Headers
			AddHtml( 15, 40, 150, 20, "<BASEFONT COLOR=#FFFFFF>Item</BASEFONT>", false, false );
			AddHtml( 165, 40, 100, 20, "<BASEFONT COLOR=#FFFFFF>Material</BASEFONT>", false, false );
			AddHtml( 275, 40, 50, 20, "<BASEFONT COLOR=#FFFFFF>Target</BASEFONT>", false, false );
			AddHtml( 335, 40, 50, 20, "<BASEFONT COLOR=#FFFFFF>Made</BASEFONT>", false, false );
			AddHtml( 395, 40, 50, 20, "<BASEFONT COLOR=#FFFFFF>Fail</BASEFONT>", false, false );
			AddHtml( 455, 40, 50, 20, "<BASEFONT COLOR=#FFFFFF>Exc</BASEFONT>", false, false );
			AddHtml( 515, 40, 50, 20, "<BASEFONT COLOR=#FFFFFF>Remove</BASEFONT>", false, false );

			int y = 60;

			for ( int i = 0; i < m_Queue.Entries.Count; i++ )
			{
				CraftQueueEntry entry = m_Queue.Entries[i];
			    int statusHue = entry.IsCompleted ? 0x3E : 0x480;	
				if ( entry.CraftItem.NameNumber > 0 )
					AddHtmlLocalized( 15, y, 140, 20, entry.CraftItem.NameNumber, 0x7FFF, false, false );
				else
					AddLabel( 15, y, statusHue, entry.CraftItem.NameString );
                // --- MANUAL RESOURCE OVERRIDE ---
                string resName = "Default";

                if (entry.ResourceType != null)
                {
                    resName = entry.ResourceType.Name;
                }
                else
                {
                    // Clean up the system name
                    string systemName = m_System.GetType().Name.Replace("Def", "").Replace("Craft", "");

                    // Hardcode the base materials
                    if (systemName == "Blacksmithy")
                        resName = "Iron Ingot";
                    else if (systemName == "Carpentry" || systemName == "Bowcraft")
                        resName = "Board";
                    else if (systemName == "Tailoring")
                    {
                        bool requiresCloth = false;

                        // Look at the first ingredient required to make this item
                        if (entry.CraftItem.Resources.Count > 0)
                        {
                            Type reqType = entry.CraftItem.Resources.GetAt(0).ItemType;
                            if (reqType == typeof(Server.Items.Cloth) || reqType == typeof(Server.Items.UncutCloth))
                            {
                                requiresCloth = true;
                            }
                        }

                        if (requiresCloth)
                            resName = "Cloth";
                        else
                            resName = "Leather";
                    }
                }

                // Render as pure white (1152) using the standard AddLabel method
                AddLabel(165, y, 1152, resName);
				AddLabel( 275, y, 0x480, entry.TargetAmount.ToString() );
				AddLabel( 335, y, 0x35, entry.AmountMade.ToString() );       
				AddLabel( 395, y, 0x22, entry.AmountFailed.ToString() );     
				AddLabel( 455, y, 0x3E, entry.AmountExceptional.ToString() );

				AddButton( 525, y + 3, 4017, 4019, 100 + i, GumpButtonType.Reply, 0 ); 

				y += 20;
				if ( y > 380 ) break; 
			}

			// Footer Buttons
			AddButton( 15, 405, 4014, 4016, 0, GumpButtonType.Reply, 0 );
			AddHtml( 50, 407, 100, 20, "<BASEFONT COLOR=#FFFFFF>BACK</BASEFONT>", false, false );

			// Dynamic Play/Pause Button
			AddButton( 250, 405, m_Queue.IsPaused ? 4005 : 4011, m_Queue.IsPaused ? 4007 : 4012, 1, GumpButtonType.Reply, 0 );
			AddHtml( 285, 407, 100, 20, m_Queue.IsPaused ? "<BASEFONT COLOR=#00FF00>PLAY QUEUE</BASEFONT>" : "<BASEFONT COLOR=#FF0000>PAUSE QUEUE</BASEFONT>", false, false );

			AddButton( 450, 405, 4017, 4019, 2, GumpButtonType.Reply, 0 );
			AddHtml( 485, 407, 100, 20, "<BASEFONT COLOR=#FFFFFF>CLEAR ALL</BASEFONT>", false, false );
		}

		public override void OnResponse( NetState sender, RelayInfo info )
		{
			if ( info.ButtonID == 0 ) // Back
			{
				m_From.SendGump( new CraftGump( m_From, m_System, m_Tool, null ) );
			}
            else if ( info.ButtonID == 1 ) // Play/Pause Toggle
			{
				m_Queue.IsPaused = !m_Queue.IsPaused;
				
				if ( !m_Queue.IsPaused && m_Queue.Entries.Count > 0 )
				{
					// --- AVATARS CONQUEST: Auto-Tool Replacement ---
					if ( m_Tool == null || m_Tool.Deleted || m_Tool.UsesRemaining <= 0 )
					{
						// Try to find a replacement tool of the exact same type in their backpack
						BaseTool replacement = m_From.Backpack != null ? m_From.Backpack.FindItemByType( m_Tool.GetType() ) as BaseTool : null;
						
						if ( replacement != null && !replacement.Deleted && replacement.UsesRemaining > 0 )
						{
							m_Tool = replacement; // Swap the broken tool for the new one!
							m_From.SendMessage( 0x35, "Equipped a new tool from your backpack." );
						}
						else
						{
							m_From.SendMessage( 0x22, "You do not have a working tool to continue crafting." );
							m_Queue.IsPaused = true;
							m_From.SendGump( new CraftQueueGump( m_From, m_System, m_Tool ) );
							return;
						}
					}
					// -----------------------------------------------

					m_From.SendMessage( 0x35, "Crafting queue started." );
					
					// Make sure we grab the next INCOMPLETE item, not just the top of the list
					CraftQueueEntry next = m_Queue.Entries.Find( e => !e.IsCompleted );
					
					if ( next != null )
					{
						next.CraftItem.Craft( m_From, m_System, next.ResourceType, m_Tool );
						return; // Exit here so it doesn't reopen the gump
					}
					else
					{
						m_From.SendMessage( 0x3E, "Queue is already completely finished." );
						m_Queue.IsPaused = true;
					}
				}
				else if ( !m_Queue.IsPaused && m_Queue.Entries.Count == 0 )
				{
					m_From.SendMessage( 0x22, "Your queue is empty." );
					m_Queue.IsPaused = true;
				}
				else
				{
					m_From.SendMessage( 0x22, "Crafting queue paused." );
				}

				m_From.SendGump( new CraftQueueGump( m_From, m_System, m_Tool ) );
			}
			else if ( info.ButtonID == 2 ) // Clear All
			{
				m_Queue.Entries.Clear();
				m_From.SendGump( new CraftQueueGump( m_From, m_System, m_Tool ) );
			}
			else if ( info.ButtonID >= 100 ) // Remove specific item
			{
				int index = info.ButtonID - 100;
				if ( index >= 0 && index < m_Queue.Entries.Count )
				{
					m_Queue.Entries.RemoveAt( index );
				}
				m_From.SendGump( new CraftQueueGump( m_From, m_System, m_Tool ) );
			}
		}
	}
}
