using System;
using System.IO;
using System.Collections;
using Server;
using Server.Items;

namespace Server.Commands
{
    public class GenTeleporter
    {
        public static void Initialize()
        {
            CommandSystem.Register("TelGen", AccessLevel.Administrator, new CommandEventHandler(GenTeleporter_OnCommand));
        }

        [Usage("TelGen")]
        [Description("Generates world/dungeon teleporters from a configuration file.")]
        public static void GenTeleporter_OnCommand(CommandEventArgs e)
        {
            e.Mobile.SendMessage("Generating teleporters from config, please wait.");

            int count = new TeleportersCreator().CreateTeleporters();

            e.Mobile.SendMessage("Teleporter generating complete. {0} teleporters were generated.", count);
        }

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

            public static bool FindTeleporter(Map map, Point3D p)
            {
                IPooledEnumerable eable = map.GetItemsInRange(p, 0);

                foreach (Item item in eable)
                {
                    if (item is Teleporter && !(item is KeywordTeleporter) && !(item is SkillTeleporter))
                    {
                        int delta = item.Z - p.Z;

                        if (delta >= -12 && delta <= 12)
                            m_Queue.Enqueue(item);
                    }
                }

                eable.Free();

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

                return false;
            }

            public void CreateTeleporter(Point3D pointLocation, Point3D pointDestination, Map mapLocation, Map mapDestination, bool back)
            {
                if (!FindTeleporter(mapLocation, pointLocation))
                {
                    m_Count++;
                    Teleporter tel = new Teleporter(pointDestination, mapDestination);
                    tel.MoveToWorld(pointLocation, mapLocation);
                }

                if (back && !FindTeleporter(mapDestination, pointDestination))
                {
                    m_Count++;
                    Teleporter telBack = new Teleporter(pointLocation, mapLocation);
                    telBack.MoveToWorld(pointDestination, mapDestination);
                }
            }

            public int CreateTeleporters()
            {
                string filePath = Path.Combine(Core.BaseDirectory, "Data", "Decoration", "teleporters.cfg");

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

                using (StreamReader ip = new StreamReader(filePath))
                {
                    string line;
                    while ((line = ip.ReadLine()) != null)
                    {
                        line = line.Trim();
                        
                        // Skip empty lines or comments starting with '#'
                        if (line.Length == 0 || line.StartsWith("#"))
                            continue;

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

                        // Ensure we have exactly 9 arguments: MapLoc, X, Y, Z, MapDest, X, Y, Z, TwoWay
                        if (split.Length >= 9)
                        {
                            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 mapDest = Map.Parse(split[4]);
                                int xDest = int.Parse(split[5]);
                                int yDest = int.Parse(split[6]);
                                int zDest = int.Parse(split[7]);

                                bool back = bool.Parse(split[8]);

                                if (mapLoc != null && mapDest != null)
                                {
                                    CreateTeleporter(new Point3D(xLoc, yLoc, zLoc), new Point3D(xDest, yDest, zDest), mapLoc, mapDest, back);
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Error parsing teleporter config line: {0}\n{1}", line, ex.Message);
                            }
                        }
                    }
                }

                return m_Count;
            }
        }
    }
}
