using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System;

namespace GhostSystem
{
    public class GhostRecorderBatch : MonoBehaviour
    {
        public bool test = false;
        public string SceneId;
        public float SampleRate = 0.05f;
        public List<Transform> TrackedObjects;

        private float _timer;
        private bool _isRecording;

        private bool supabaseReady = false;
        private bool sceneIdReady = false;

        private async void OnEnable()
        {
            SupabaseManager.OnSuperbaseReady += HandleSupabaseReady;
            RoomManager.OnSceneIdReady += HandleSceneIdReady;
        }

        private void OnDisable()
        {
            SupabaseManager.OnSuperbaseReady -= HandleSupabaseReady;
            RoomManager.OnSceneIdReady -= HandleSceneIdReady;
        }

        private void HandleSupabaseReady()
        {
            supabaseReady = true;
        }

        private void HandleSceneIdReady(string id)
        {
            SceneId = id;
            sceneIdReady = true;
        }

        private async void Update()
        {
            if (test) await TestInsert();
            if (!_isRecording) return;

            _timer += Time.deltaTime;
            if (_timer >= SampleRate)
            {
                _timer = 0f;
                foreach (var obj in TrackedObjects)
                {
                    var frame = new GhostFrame(SceneId, obj.name, obj.position, obj.rotation);
                    await InsertFrame(frame);
                }
            }
        }

        private async Task InsertFrame(GhostFrame frame)
        {
            var position = new Vector3Serializable
            {
                x = frame.Position.x,
                y = frame.Position.y,
                z = frame.Position.z
            };
            var rotation = new QuaternionSerializable
            {
                x = frame.Rotation.x,
                y = frame.Rotation.y,
                z = frame.Rotation.z,
                w = frame.Rotation.w
            };

            var data = new FrameModel
            {
                UserId = SupabaseManager.instance.userId,
                SceneId = frame.SceneId,
                ObjectId = frame.ObjectId,
                Timestamp = frame.Timestamp.ToString("o"),
                PositionJson = JsonConvert.SerializeObject(position),
                RotationJson = JsonConvert.SerializeObject(rotation)
            };

            Debug.Log($"Insert frame with user_id: {SupabaseManager.instance.userId}");

            await SupabaseManager.instance.supabase.From<FrameModel>().Insert(data);
        }

        public void StartRecording()
        {
            if (!supabaseReady || !sceneIdReady) return;
            _isRecording = true;
            Debug.Log($"Recording {SceneId}");
        }

        public void StopRecording()
        {
            _isRecording = false;
            sceneIdReady = false;
            Debug.Log($"Stop recording: {SceneId}");
        }

        private async Task TestInsert()
        {
            var pos = new Vector3Serializable { x = 1f, y = 2f, z = 3f };
            var rot = new QuaternionSerializable { x = 0f, y = 0f, z = 0f, w = 1f };

            var data = new FrameModel
            {
                UserId = SupabaseManager.instance.userId,
                SceneId = "testScene",
                ObjectId = "testObject",
                Timestamp = DateTime.UtcNow.ToString("o"),
                PositionJson = JsonConvert.SerializeObject(pos),
                RotationJson = JsonConvert.SerializeObject(rot)
            };

            Debug.Log(JsonConvert.SerializeObject(data));  // Schau hier, ob es nur Strings sind.

            await SupabaseManager.instance.supabase.From<FrameModel>().Insert(data);
        }
    }
}

