using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;

public class DatabaseSavePose : MonoBehaviour
{
    public ConfigReader Config;
    public float TimeBetweenSaves = 1.0f; 
    //private string ClientConnection;
    //private string DatabaseName;
    private IMongoCollection<BsonDocument> collection;
    private MongoClient client;
    private IMongoDatabase db;
    private float t = 0f;
    void Start()
    {
        Connect();
        _map();
    }

    public void Connect()
    {
        string ClientConnection = Config.configuration.Database.ClientConnection;
        string DatabaseName = Config.configuration.Database.DatabaseName;
        string coll = Config.configuration.Database.DBCollection; 
        
        client = new MongoClient(ClientConnection);
        db = client.GetDatabase(DatabaseName);
        collection = db.GetCollection<BsonDocument>(coll);
    }


    private void _map()
    {
        BsonClassMap.RegisterClassMap<Vector3>(cm =>
        {
            cm.AutoMap();
            cm.SetIgnoreExtraElements(true);
        });
        BsonClassMap.RegisterClassMap<Quaternion>(cm =>
        {
            cm.AutoMap();
            cm.SetIgnoreExtraElements(true);
        });
        BsonClassMap.RegisterClassMap<Pose>(cm =>
        {
            cm.AutoMap();
            cm.SetIgnoreExtraElements(true);
        });
    }

    void Update()
    {
        t += Time.deltaTime;
        if (t > TimeBetweenSaves)
        {
            //save to database
            Pose p = new Pose { item = "linerobot", 
                                time = Time.time, 
                                position = transform.position,  
                                quaternion = transform.rotation};
            var bson = p.ToBsonDocument();
            collection.InsertOne(bson);
            t = 0f;
        }
    }
}
public class Pose
{
    public string item;
    public float time;
    public Vector3 position;
    public Quaternion quaternion;
}