using UnityEngine;

public class ResourceManager : MonoBehaviour
{
    public GameObject LoadModel(int id)
    {
        GameObject characterContainer = new GameObject($"CharLoaded_{id:X4}");

        GameObject mesh = GameObject.CreatePrimitive(PrimitiveType.Cube);
        mesh.transform.SetParent(characterContainer.transform);

        BoxCollider boxCollider = mesh.GetComponent<BoxCollider>();
        if (boxCollider != null)
        {
            GameObject.Destroy(boxCollider);
        }

        float height = id == 1 ? 150f : 60f;
        mesh.transform.localScale = new Vector3(30f, height, 30f);

        // 5. Поднимаем визуальную часть на половину высоты
        mesh.transform.localPosition = new Vector3(0, height / 2f, 0);

        // 6. Добавляем коллайдер и контроллер КОНТЕЙНЕРУ, а не визуальной части
        CapsuleCollider capsuleCollider = characterContainer.AddComponent<CapsuleCollider>();
        capsuleCollider.height = height;
        capsuleCollider.radius = 50f;
        capsuleCollider.center = new Vector3(0, height / 2f, 0); // Центр на половине высоты

        characterContainer.AddComponent<CharacterController>();

        return characterContainer;
    }

    public static int ConvertGameCoordinate(uint gameCoord)
    {
        int value30bit = (int)(gameCoord & 0x3FFFFFFF);
        if ((gameCoord & 0x40000000) != 0)
        {
            return value30bit - 0x40000000;
        }
        else
        {
            return value30bit;
        }
    }

    public static float ConvertGameRotation(uint gameRot)
    {
        return gameRot * 45f - 180f;
    }

    public GameObject CharLoad(int modelId)
    {
        GameObject obj = LoadModel(modelId);
        obj.name = $"ModelTemplate_{modelId:X4}";
        obj.SetActive(false);
        return obj;
    }

    public GameObject CharInit(GameObject obj, int id, uint gameX, uint gameY, uint gameZ, uint gameRot)
    {
        GameObject characterInstance = Instantiate(obj);

        var ctrl = characterInstance.GetComponent<CharacterController>();
        ctrl.CharacterId = id;
        characterInstance.name = $"{id:X4}";  //rename for normal script ID
        float x = ConvertGameCoordinate(gameX);
        float y = ConvertGameCoordinate(gameY);
        float z = ConvertGameCoordinate(gameZ);
        float rotation = ConvertGameRotation(gameRot);

        characterInstance.transform.position = new Vector3(x, y, z);
        characterInstance.transform.rotation = Quaternion.Euler(0, rotation, 0);
        characterInstance.SetActive(true);

        if (id == 1 && ControlsController.Instance != null)
        {
            ControlsController.Instance.SetControlledObject(characterInstance);
        }

        return characterInstance;
    }
}