using LiteDB;

namespace Dacryptero.DB.Migration
{
    /// <summary>
    /// Migrate the Database from Version 0 to 1. <br/>
    /// This introduces a new cached field for Attributes that points on their Person.
    /// </summary>
    public class Version0Migration : IMigrator
    {
        public void Migrate(LiteDatabase database, DBConfig config, bool confidential)
        {
            Serilog.Log.Information("Migrate Database {name} (conf={conf}) to Version 1 ...", config.Name, confidential);
            var persons = database.GetCollection(confidential ? "conf_person_data" : "person");
            var attributes = database.GetCollection("attribute");

            int personCount = 0, attrCount = 0;
            foreach (var person in persons.Query().ToEnumerable())
            {
                personCount++;
                var id = person["_id"];
                foreach (var attr in person["Attributes"].AsArray)
                {
                    attrCount++;
                    var realAttr = attributes.FindById(attr["$id"]);
                    realAttr.AsDocument["PersonId"] = id;
                    attributes.Update(realAttr);
                    if ((attrCount % 5000) == 0)
                        Serilog.Log.Debug("  Person: {person:#,#0} Attributes: {attribute:#,#0}", personCount, attrCount);
                }
            }
            database.UserVersion = 1;
            Serilog.Log.Information("Migrated Database {name} (conf={conf}) to Version 1", config.Name, confidential);
        }
    }
}