using Postgrest.Attributes;
using Postgrest.Models;
using UnityEngine;
using Newtonsoft.Json;
using System;

namespace GhostSystem
{
    [Table("object_positions")]
    public class FrameModel : BaseModel
    {

        [Column("user_id")]
        public string UserId { get; set; }

        [Column("scene_id")]
        public string SceneId { get; set; }

        [Column("object_id")]
        public string ObjectId { get; set; }

        [Column("timestamp")]
        public string Timestamp { get; set; } // ISO 8601 string

        [Column("position")]
        public string PositionJson { get; set; } // stored as JSONB

        [Column("rotation")]
        public string RotationJson { get; set; } // stored as JSONB

        public static FrameModel FromGhostFrame(GhostFrame frame)
        {
            return new FrameModel
            {
                UserId = SupabaseManager.instance.userId,
                SceneId = frame.SceneId,
                ObjectId = frame.ObjectId,
                Timestamp = frame.Timestamp.ToString("o"), // "o" für ISO 8601
                PositionJson = JsonConvert.SerializeObject(new Vector3Serializable
                {
                    x = frame.Position.x,
                    y = frame.Position.y,
                    z = frame.Position.z,
                }),
                RotationJson = JsonConvert.SerializeObject(new QuaternionSerializable
                {
                    x = frame.Rotation.x,
                    y = frame.Rotation.y,
                    z = frame.Rotation.z,
                    w = frame.Rotation.w
                })
            };
        }
        
        [JsonIgnore]
        public DateTime TimestampParsed => DateTime.Parse(Timestamp).ToUniversalTime();

        [JsonIgnore]
        public Vector3 Position => JsonConvert.DeserializeObject<Vector3Serializable>(PositionJson).ToVector3();
        [JsonIgnore]
        public Quaternion Rotation => JsonConvert.DeserializeObject<QuaternionSerializable>(RotationJson).ToQuaternion();

    }
}

