using Common;
using RpcComponents;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.NetCode;
using Unity.Rendering;
using Unity.Transforms;
using UnityEngine;

namespace Server
{
    [WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]
    public partial struct ServerProcessGameEntryRequestSystem : ISystem
    {
        public void OnCreate(ref SystemState state)
        {
            var builder = new EntityQueryBuilder(Allocator.Temp).WithAll<TdTeamRequest, ReceiveRpcCommandRequest>();
            state.RequireForUpdate(state.GetEntityQuery(builder));
            state.RequireForUpdate<TdPrefabs>();
        }

        public void OnUpdate(ref SystemState state)
        {
            var ecb = new EntityCommandBuffer(Allocator.Temp);
            var characterPrefab  = SystemAPI.GetSingleton<TdPrefabs>().Character;
            
            foreach (var (teamRequest, requestSource, requestEntity) in SystemAPI.Query<TdTeamRequest, ReceiveRpcCommandRequest>().WithEntityAccess())
            {
                //destroy request entity that only holds request
                ecb.DestroyEntity(requestEntity);
                
                //sync server connection entity with client connection entity
                ecb.AddComponent<NetworkStreamInGame>(requestSource.SourceConnection);

                var requestedTeam  = teamRequest.Value;
                var requestedColor = teamRequest.Color;
                var clientId    = SystemAPI.GetComponent<NetworkId>(requestSource.SourceConnection).Value;
                    
                Debug.Log($"Server is assigning ClientId {clientId} to team {requestedTeam}");
                
                var newCharacter = ecb.Instantiate(characterPrefab);
                var spawnPosition     = new float3(0f, 1f, 0f);
                var newTransform      = LocalTransform.FromPosition(spawnPosition);

                ecb.SetComponent(newCharacter, newTransform);
                ecb.SetName(newCharacter, "Character");
                
                ecb.SetComponent(newCharacter, new TdTeam { Value = requestedTeam });
                ecb.AddComponent(newCharacter, new GhostOwner { NetworkId = clientId});
                
                //Destroy character prefab, when client disconnects
                ecb.AppendToBuffer(requestSource.SourceConnection, new LinkedEntityGroup{Value = newCharacter});
            }
            
            ecb.Playback(state.EntityManager);
        }
    }
}