using System;
using System.IO;
using System.Collections;
using Server;
using Server.Items;
using Server.Custom.InnRooms; // Ensure it can find our InnDoor!

namespace Server.Commands
{
    public class GenInnDoors
    {
        public static void Initialize()
        {
            CommandSystem.Register("InnGen", AccessLevel.Administrator, new CommandEventHandler(GenInnDoors_OnCommand));
        }

        [Usage("InnGen")]
        [Description("Generates Inn Doors from a configuration file.")]
        public static void GenInnDoors_OnCommand(CommandEventArgs e)
        {
            e.Mobile.SendMessage("Generating Inn Doors from config, please wait.");

            int count = new InnDoorCreator().CreateDoors();

            e.Mobile.SendMessage("Inn Door generation complete. {0} doors were generated.", count);
        }

        public class InnDoorCreator
        {
            private int m_Count;
            private static Queue m_Queue = new Queue();

            // Finds and deletes existing InnDoors at the target location to prevent stacking
            public static bool FindExistingDoor(Map map, Point3D p)
            {
                IPooledEnumerable eable = map.GetItemsInRange(p, 0);

                foreach (Item item in eable)
                {
                    if (item is InnDoor)
                    {
                        int delta = item.Z - p.Z;

                        if (delta >= -12 && delta <= 12) // Uses your existing Z-delta logic
                            m_Queue.Enqueue(item);
                    }
                }

                eable.Free();

                while (m_Queue.Count > 0)
                    ((Item)m_Queue.Dequeue()).Delete();

                return false;
            }

            public void CreateDoor(Point3D loc, Map mapLoc, Point3D roomLoc, Map roomMap, int itemID)
            {
                if (!FindExistingDoor(mapLoc, loc))
                {
                    m_Count++;
                    
                    // Uses our new parameterized constructor for custom facings!
                    InnDoor door = new InnDoor(itemID);
                    
                    // Wire up the void room coordinates automatically
                    door.RoomLocation = roomLoc;
                    door.RoomMap = roomMap;
                    
                    door.MoveToWorld(loc, mapLoc);
                }
            }

            public int CreateDoors()
            {
                // Reads from the same Decoration directory[cite: 3]
                string filePath = Path.Combine(Core.BaseDirectory, "Data", "Decoration", "inndoors.cfg");

                if (!File.Exists(filePath))
                {
                    Console.WriteLine("Warning: {0} not found. No Inn Doors generated.", filePath);
                    return 0;
                }

                using (StreamReader ip = new StreamReader(filePath))
                {
                    string line;
                    while ((line = ip.ReadLine()) != null)
                    {
                        line = line.Trim();
                        
                        if (line.Length == 0 || line.StartsWith("#"))
                            continue;

                        string[] split = line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);

                        // We need at least 8 arguments (Door Map/X/Y/Z and Room Map/X/Y/Z)
                        if (split.Length >= 8)
                        {
                            try
                            {
                                Map mapLoc = Map.Parse(split[0]);
                                int xLoc = int.Parse(split[1]);
                                int yLoc = int.Parse(split[2]);
                                int zLoc = int.Parse(split[3]);

                                Map mapRoom = Map.Parse(split[4]);
                                int xRoom = int.Parse(split[5]);
                                int yRoom = int.Parse(split[6]);
                                int zRoom = int.Parse(split[7]);

                                // Optional 9th argument: ItemID for custom facings! Defaults to 0x6E5 (1765) if missing.
                                int itemID = 1765; 
                                if (split.Length >= 9)
                                {
                                    // Handles both hex (0x6F3) and integer (1779) formats
                                    if (split[8].StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                                        itemID = Convert.ToInt32(split[8], 16);
                                    else
                                        itemID = int.Parse(split[8]);
                                }

                                if (mapLoc != null && mapRoom != null)
                                {
                                    CreateDoor(new Point3D(xLoc, yLoc, zLoc), mapLoc, new Point3D(xRoom, yRoom, zRoom), mapRoom, itemID);
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Error parsing Inn Door config line: {0}\n{1}", line, ex.Message);
                            }
                        }
                    }
                }

                return m_Count;
            }
        }
    }
}
