using System.Collections.Generic;
using Intrepid.Gameplay.Journey;
using Intrepid.Gameplay.Prototyping.Sockets;
using Intrepid.Utilities;
using Sirenix.OdinInspector;
using UnityEngine;

namespace Intrepid.Gameplay.Prototyping
{
    public class InteractableSocketModelPrototype : InteractableModelPrototype
    {
        [GroupConfigurations, SerializeField, ReadOnly]  private int sizeX = 1;
        [GroupConfigurations, SerializeField, ReadOnly] private int sizeZ = 1;

        [GroupDebug, SerializeField, Min(1)] private int x = 1;
        [GroupDebug, SerializeField, Min(1)] private int z = 1;
        
        [GroupConfigurations, SerializeField] private JSocketFace socketFace;
        [GroupInjections, SerializeField] private StageSocketDeploymentPoint deploymentPoint;
        [GroupInjections, SerializeField] private StageSocketChangeTrigger changeTrigger;
        [GroupDebug, SerializeField, ReadOnly] private StageManager stageManager;

        public string StageId => stageManager.StageTag.StageId;
        [GroupDebug, ShowInInspector, ReadOnly] public string EndpointId { get; private set; }
        public JSocketFace SocketFace
        {
            get => socketFace;
            set => socketFace = value;
        }
        public Vector3 DeploymentPoint => deploymentPoint.DeploymentPoint;
        public Vector2 DeploymentDirection => deploymentPoint.DeploymentDirection;

        public override void SetStageManager(StageManager sm)
        {
            stageManager = sm;
            var stageTag = sm.StageTag;
            var position = transform.position;
            EndpointId = JourneyService.Instance.GetEndpoint(stageTag, position, socketFace);
        }
        
        protected override void DebugResize()
        {
            x = Mathf.Max(1, x);
            z = Mathf.Max(1, z);
            sizeX = x;
            sizeZ = z;
        }

        protected override void Generate()
        {
            var vertices = new List<Vector3>();
            var triangles = new List<int>();
            var uvs = new List<Vector2>();
            
            MeshUtils.AddCubeFaces(vertices, triangles, uvs,
                sizeX, 3, sizeZ,
                sizeX * 0.5f, 1.5f, sizeZ * 0.5f);
            
            PrototypeModel.BuildMesh(new MeshData(
                vertices.ToArray(),
                triangles.ToArray(),
                uvs.ToArray()));
            
            PrototypeModel.BoxCollider.size = new Vector3(sizeX, 3f, sizeZ);
            PrototypeModel.BoxCollider.center = new Vector3(0f, 0f, 0f);
            PrototypeModel.transform.localPosition = new Vector3(0f, 1.5f, 0f);
        }
    }
}