using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Oxide.Core;
using UnityEngine;

namespace Oxide.Plugins
{
    [Info("IndustrialRecycler", "Marte6", "1.0.0")]
    [Description("Automate recycling by attaching storage and adaptors to recyclers.")]
    class IndustrialRecycler : RustPlugin
    {
        #region Fields
        private static IndustrialRecycler _instance;
        private PluginConfig _config;
        private Dictionary<ulong, RecyclerManager> _entitysOnRecyclers = new Dictionary<ulong, RecyclerManager>();
        private Dictionary<ulong, ulong> _playersRecyclers = new Dictionary<ulong, ulong>();
        private const string RecyclerPrefabPath = "assets/bundled/prefabs/static/recycler_static.prefab";
        private const string StorageInputPrefabPath = "assets/content/vehicles/boats/rowboat/subents/rowboat_storage.prefab";
        private const string StorageOutputPrefabPath = "assets/prefabs/deployable/hot air balloon/subents/hab_storage.prefab";
        private const string AdaptorPrefabPath = "assets/prefabs/deployable/playerioents/industrialadaptors/storageadaptor.deployed.prefab";
        private const string SmallGeneratorPrefabName = "electric.generator.small";
        private const ulong RecyclerSkinID = 3341430953;
        #endregion

        #region Game Hooks
        private void Init()
        {
            foreach (var command in _config.Commands)
            {
                cmd.AddChatCommand(command, this, nameof(HandleTestCommand));
            }
        }

        private void OnServerInitialized()
        {
            _instance = this;

            var existingRecyclers = UnityEngine.Object.FindObjectsOfType<Recycler>();
            foreach (var recycler in existingRecyclers)
            {
                if (recycler.OwnerID != 0UL)
                {
                    recycler.gameObject.AddComponent<RecyclerManager>();
                }
            }
        }

        private void Unload()
        {
            var recyclers = UnityEngine.Object.FindObjectsOfType<RecyclerManager>();
            foreach (var recycler in recyclers)
            {
                UnityEngine.Object.Destroy(recycler);
            }

            _entitysOnRecyclers.Clear();
            _playersRecyclers.Clear();
        }

        private void OnItemAddedToContainer(ItemContainer container, Item item)
        {
            if (container?.entityOwner is Recycler recycler && _entitysOnRecyclers.TryGetValue(recycler.net.ID.Value, out var recyclerManager))
            {
                HandleItemsInRecycler(recyclerManager, item);
            }
        }

        private void OnEntityBuilt(Planner planner, GameObject buildingObject)
        {
            var player = planner?.GetOwnerPlayer();
            var entity = buildingObject.GetComponent<BaseEntity>();

            if (player == null || entity == null || entity.ShortPrefabName != "generator.small" || entity.skinID != RecyclerSkinID)
                return;

            if (_playersRecyclers.Count(pair => pair.Value == player.userID) >= _config.Limit)
            {
                player.ChatMessage("You have reached the recycler limit.");
                timer.Once(1, () => ProvideRecyclerToPlayer(player));
                NextTick(() => entity?.Kill());
                return;
            }

            if (!DeployRecyclerSetup(player, entity))
            {
                player.ChatMessage("Recycler must be placed on a construction block.");
                timer.Once(1, () => ProvideRecyclerToPlayer(player));
            }

            NextTick(() => entity?.Kill());
        }

        private object CanPickupEntity(BasePlayer player, IndustrialStorageAdaptor entity)
        {
            if (_entitysOnRecyclers.ContainsKey(entity.net.ID.Value))
            {
                _entitysOnRecyclers[entity.net.ID.Value].Recycler.Kill();
                ProvideRecyclerToPlayer(player);
                return false;
            }

            return null;
        }

        private object OnEntityKill(Recycler recycler)
        {
            if (_playersRecyclers.ContainsKey(recycler.net.ID.Value))
            {
                _playersRecyclers.Remove(recycler.net.ID.Value);
                RemoveRecyclerEntities(recycler);
            }

            return null;
        }
        #endregion

        #region Main
        private void HandleTestCommand(BasePlayer player, string command, string[] args)
        {
            ProvideRecyclerToPlayer(player);
        }

        private void ProvideRecyclerToPlayer(BasePlayer player)
        {
            var recyclerItem = ItemManager.CreateByName(SmallGeneratorPrefabName, 1, RecyclerSkinID);
            recyclerItem.name = "Recycler";
            player.inventory.GiveItem(recyclerItem);
        }

        private bool DeployRecyclerSetup(BasePlayer player, BaseEntity entity)
        {
            var foundationBlock = DetectSupportingFoundation(entity);
            if (foundationBlock == null)
                return false;

            var spawnedRecycler = SpawnRecyclerWithComponents(player, entity, foundationBlock);
            if (spawnedRecycler == null)
                return false;

            spawnedRecycler.gameObject.AddComponent<RecyclerManager>();
            return true;
        }

        private BuildingBlock DetectSupportingFoundation(BaseEntity entity)
        {
            Vector3 origin = entity.transform.position + Vector3.up * 0.1f;
            Ray ray = new(origin, Vector3.down);

            if (Physics.Raycast(ray, out RaycastHit hitInfo, 4f, LayerMask.GetMask("Construction")))
            {
                return hitInfo.GetEntity() as BuildingBlock;
            }
            return null;
        }

        private Recycler SpawnRecyclerWithComponents(BasePlayer player, BaseEntity entity, BuildingBlock foundationBlock)
        {
            var recycler = SpawnEntity(RecyclerPrefabPath, foundationBlock, player, entity.transform.position, entity.transform.rotation * Quaternion.Euler(0, 270, 0)) as Recycler;
            if (recycler == null)
                return null;

            var inputStorage = SpawnEntity(StorageInputPrefabPath, recycler, player, new Vector3(-1.0f, 0.72f, 0.31f), Quaternion.Euler(90, 90, 180));
            SpawnEntity(AdaptorPrefabPath, inputStorage, player, new Vector3(0.00f, -0.15f, -0.25f), Quaternion.Euler(180, 90, 270));
            var outputStorage = SpawnEntity(StorageOutputPrefabPath, recycler, player, new Vector3(-0.9f, 0.72f, -0.09f), Quaternion.Euler(180, 90, 180));
            SpawnEntity(AdaptorPrefabPath, outputStorage, player, new Vector3(0.00f, 0.26f, -0.05f), Quaternion.Euler(0, 90, 0));

            return recycler;
        }

        private BaseEntity SpawnEntity(string prefabPath, BaseEntity parent, BasePlayer player, Vector3 position, Quaternion rotation)
        {
            var entity = GameManager.server.CreateEntity(prefabPath, Vector3.zero, Quaternion.identity, true);
            entity.OwnerID = player.userID;

            if (parent != null)
            {
                entity.SetParent(parent, true);
            }

            if (parent is BuildingBlock)
            {
                entity.transform.position = position;
                entity.transform.rotation = rotation;
            }
            else
            {
                entity.transform.localPosition = position;
                entity.transform.localRotation = rotation;
            }

            entity.Spawn();
            entity.SendNetworkUpdateImmediate();
            return entity;
        }

        private void HandleItemsInRecycler(RecyclerManager recyclerManager, Item item)
        {
            if (item.position < 6)
            {
                recyclerManager.Recycler.StartRecycling();
            }
            else
            {
                if (!item.MoveToContainer(recyclerManager.OutputContainer.inventory))
                {
                    recyclerManager.Recycler.StopRecycling();
                }
            }
        }

        private void RemoveRecyclerEntities(Recycler recycler)
        {
            var children = recycler.children;
            foreach (var child in children)
            {
                if (_entitysOnRecyclers.ContainsKey(child.net.ID.Value))
                {
                    _entitysOnRecyclers.Remove(child.net.ID.Value);
                }
            }

            if (_entitysOnRecyclers.ContainsKey(recycler.net.ID.Value))
            {
                _entitysOnRecyclers.Remove(recycler.net.ID.Value);
            }
        }
        #endregion

        #region Configs
        private class PluginConfig
        {
            [JsonProperty("Commands")]
            public List<string> Commands { get; set; }

            [JsonProperty("Limit Per Player")]
            public int Limit { get; set; }

            [JsonProperty("Version")]
            public VersionNumber Version { get; set; }
        }

        protected override void LoadConfig()
        {
            base.LoadConfig();

            try
            {
                _config = Config.ReadObject<PluginConfig>() ?? throw new Exception();

                if (_config.Version < Version)
                {
                    UpdateConfiguration();
                }

                SaveConfig();
            }
            catch
            {
                PrintError("There is an error in your configuration file. Default values will be used.");
                LoadDefaultConfig();
            }
        }

        protected override void LoadDefaultConfig()
        {
            _config = CreateDefaultConfig();
        }

        protected override void SaveConfig()
        {
            Config.WriteObject(_config);
        }

        private void UpdateConfiguration()
        {
            PrintWarning("Configuration change detected! Updating settings.");
            _config.Version = Version;
            PrintWarning("Configuration update completed!");
        }

        private PluginConfig CreateDefaultConfig()
        {
            return new PluginConfig
            {
                Commands = new List<string> { "teste", "testee", "testeeee" },
                Limit = 1,
                Version = Version,
            };
        }
        #endregion

        #region MonoBehaviour
        private class RecyclerManager : MonoBehaviour
        {
            public Recycler Recycler { get; private set; }
            public StorageContainer InputContainer { get; private set; }
            public StorageContainer OutputContainer { get; private set; }

            private void Awake()
            {
                Recycler = GetComponent<Recycler>();
                InputContainer = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c.name == StorageInputPrefabPath);
                OutputContainer = Recycler.children.OfType<StorageContainer>().FirstOrDefault(c => c.name == StorageOutputPrefabPath);

                if (InputContainer == null || OutputContainer == null)
                {
                    Destroy(this);
                    _instance.PrintError("Storage containers missing.");
                    return;
                }

                var adaptorInputContainer = InputContainer.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
                if (adaptorInputContainer != null)
                    _instance._entitysOnRecyclers[adaptorInputContainer.net.ID.Value] = this;

                var adaptorOutputContainer = OutputContainer.children.OfType<IndustrialStorageAdaptor>().FirstOrDefault();
                if (adaptorOutputContainer != null)
                    _instance._entitysOnRecyclers[adaptorOutputContainer.net.ID.Value] = this;

                _instance._entitysOnRecyclers[Recycler.net.ID.Value] = this;
                _instance._playersRecyclers[Recycler.net.ID.Value] = Recycler.OwnerID;

                InputContainer.inventory.capacity = 48;
                OutputContainer.inventory.capacity = 48;

                InvokeRepeating(nameof(MoveItemsToRecycler), 0f, 20f);
            }

            private void MoveItemsToRecycler()
            {
                int nextSlot = 0;
                foreach (var item in InputContainer.inventory.itemList.ToList())
                {
                    if (nextSlot >= 6)
                        break;

                    if (Recycler.inventory.GetSlot(nextSlot) == null)
                    {
                        item.MoveToContainer(Recycler.inventory, nextSlot);
                        nextSlot++;
                    }
                }
            }

            private void OnDestroy()
            {
                CancelInvoke(nameof(MoveItemsToRecycler));
            }
        }
        #endregion
    }
}