using AyaNova.Models;
using AyaNova.Biz;

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using System.Reflection;
using System;


namespace AyaNova.Biz
{

    /// <summary>
    /// Returns owner Id if the object exists or 0 if exists but there is no owner ID property or -1 if the object doesn't exist
    /// </summary>
    internal static class AyaObjectOwnerId
    {
        internal static long Get(AyaTypeId o, AyContext ct)
        {
            if (o.IsEmpty) return -1;


            //Get the type of the model of AyaObject
            Type t = Type.GetType("AyaNova.Models." + o.ObjectType.ToString());

            //Run a find query on the db context based on the model's type
            object record = ct.Find(t, o.ObjectId);
            if (record == null)
            {
                return -1;
            }


            PropertyInfo ownerIdPropertyInfo = record.GetType().GetProperty("OwnerId");

            if (ownerIdPropertyInfo == null)
                return 0;//object exists and it doesn't have an ownerID property


            long ret = (long)ownerIdPropertyInfo.GetValue(record, null);

            return ret;

        }

    }

}//eons 
