using System;
using System.Collections.Generic;
using ConVar;
using Facepunch;
using Facepunch.Rust;
using Network;
using Newtonsoft.Json;
using Oxide.Core;
using Oxide.Core.Libraries.Covalence;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Cui;
using UnityEngine;
using UnityEngine.Assertions;

namespace Oxide.Plugins
{
    [Info("Aa", "Marte6", "1.0.0")]
    [Description("Aa")]
    class Aa : RustPlugin
    {
        private Configuration _config;

        private void Init()
        {
            RegisterCommands();
        }

        private void RegisterCommands()
        {
            foreach (var command in _config.Commands)
            {
                cmd.AddChatCommand(command, this, nameof(CmdTest));
            }
        }

        private void OnEntityBuilt(Planner plan, GameObject obj)
        {
            var player = plan?.GetOwnerPlayer();
            var entity = obj.GetComponent<BaseEntity>();
            Puts(entity.ShortPrefabName);

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

            var position = entity.transform.position;
            var rotation = Quaternion.identity;
            Recycler recycler = GameManager.server.CreateEntity("assets/bundled/prefabs/static/recycler_static.prefab", position, rotation) as Recycler;

            entity?.Kill();

            if (recycler == null)
            {
                Puts("Falha ao criar a recycler.");
                return;
            }

            Puts($"Raycasting from position: {position}");

            // Ajustar a posição do raycast para um pouco acima
            var raycastPosition = position + new Vector3(0, 1f, 0);
            RaycastHit hit;
            if (UnityEngine.Physics.Raycast(raycastPosition, Vector3.down, out hit, 10f))
            {
                var groundEntity = hit.GetEntity();

                if (groundEntity != null && groundEntity is BuildingBlock)
                {
                    recycler.SetParent(groundEntity);
                    recycler.transform.localPosition = new Vector3(0, 1.0f, 0);
                    recycler.transform.localRotation = Quaternion.identity;
                }
                else
                {
                    Puts($"Entidade encontrada abaixo: {groundEntity?.ShortPrefabName}"); // Mostra a entidade encontrada
                }
            }
            else
            {
                Puts("Nenhum chão ou fundação detectado abaixo.");
            }

            recycler.Spawn();
            recycler.SendNetworkUpdateImmediate();

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

        private void OnEntityGroundMissing(Recycler recycler)
        {
            // Potentially handle the missing ground scenario for recyclers if needed
        }

        private void CmdTest(BasePlayer player, string command, string[] args)
        {
            Item item = ItemManager.CreateByName("electric.generator.small", 1, 3341430953);
            item.name = "Recycler";
            player.inventory.GiveItem(item);
        }

        #region Configuration

        private class Configuration
        {
            [JsonProperty("Commands")]
            public List<string> Commands { get; set; }

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

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

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

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

                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 UpdateConfigValues()
        {
            PrintWarning("Configuration change detected! Updating settings.");
            _config.Version = Version;
            PrintWarning("Configuration update completed!");
        }

        private Configuration CreateDefaultConfig()
        {
            return new Configuration
            {
                Commands = new List<string> { "teste", "testee", "testeeee" },
            };
        }

        #endregion
    }
}