using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Physics;
using Unity.Rendering;
using UnityEngine;
using UnityEngine.Rendering;

namespace Common
{
    [UpdateInGroup(typeof(SimulationSystemGroup), OrderFirst = true)]
    [WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation | WorldSystemFilterFlags.ClientSimulation)]
    public partial struct InitializeCharacterSystem : ISystem
    {
        public void OnCreate(ref SystemState state)
        {
        }

        public void OnUpdate(ref SystemState state)
        {
            var ecb = new EntityCommandBuffer(Allocator.Temp);
            foreach (var (physicsMass, config, newCharacterEntity) in SystemAPI.Query<RefRW<PhysicsMass>, RefRO<CharacterConfig>>().WithAny<NewCharacterTag>().WithEntityAccess())
            {
                physicsMass.ValueRW.InverseInertia[0] = 0;
                physicsMass.ValueRW.InverseInertia[1] = 0;
                physicsMass.ValueRW.InverseInertia[2] = 0;

                var requestedColor = config.ValueRO.Color;
                var color = new float4(requestedColor.r, requestedColor.g, requestedColor.b, requestedColor.a);
                ecb.AddComponent(newCharacterEntity, new URPMaterialPropertyBaseColor{Value = color});
                ecb.RemoveComponent<NewCharacterTag>(newCharacterEntity);
            }

            ecb.Playback(state.EntityManager);
        }

        public void OnDestroy(ref SystemState state)
        {
        
        }
    }
}
