/*
 * Copyright (c)2009-2025 DemiVision, LLC. All Rights Reserved. The information
 * herein is the CONFIDENTIAL and PROPRIETARY information of DemiVision, LLC.
 */

using Plugin.Firebase.Firestore;

using DXLib.Data;
using DXLib.Data.Model;

using DXLib.Utils;

namespace iStatVball3;

/*
 * Encapsulates information related to the device and operating system used by a User for a specific login session.
 */ 
public class Session : DXModel
{
	/* Constants */
	public const string CollectionKey = "Sessions";

	// Platforms
	public const string Apple = "iOS";
	public const string Android = "Android";

	// Idioms
	public const string Tablet = "Tablet";
	public const string Phone = "Phone";

    /* Properties */

    // App properties
    [FirestoreProperty("AppVersion")] public string AppVersion { get; set; }

    // Device properties
    [FirestoreProperty("Platform")] public string Platform { get; set; }
    [FirestoreProperty("Idiom")] public string Idiom { get; set; }

    [FirestoreProperty("Model")] public string Model { get; set; }
    [FirestoreProperty("Manufacturer")] public string Manufacturer { get; set; }
    [FirestoreProperty("DeviceName")] public string DeviceName { get; set; }
    [FirestoreProperty("Version")] public string Version { get; set; }

    [FirestoreProperty("ScreenWd")] public int ScreenWd { get; set; }
    [FirestoreProperty("ScreenHt")] public int ScreenHt { get; set; }

	// Parent user
	[FirestoreProperty("UserId")] public string UserId { get; set; }

	/* Methods */
	public Session()
	{
		BaseCollectionKey = CollectionKey;
	}

	/* CRUD */

	// Creates and persists new session (batched)
	public static void Create( IWriteBatch batch, string userId )
	{
		Session session = new()
		{
			// Populate app properties
			AppVersion = App.AppVersion,

			// Populate device properties
			Platform = DXDevice.PlatformOS,
			Idiom = DXDevice.Idiom,

			Model = DXDevice.Model,
			Manufacturer = DXDevice.Manufacturer,
			DeviceName = DXDevice.Name,
			Version = DXDevice.VersionString,

			ScreenWd = (int)DXDevice.GetScreenWd(),
			ScreenHt = (int)DXDevice.GetScreenHt(),

			// Link to parent user
			UserId = userId
		};

		session.Create( batch );
	}

	// Returns last N sessions for specified user
	public static async Task<List<Session>> Read( string userId, int limit )
	{
        // Sort chronologically descending
        IQuerySnapshot<Session> query = await DXData.Firestore.GetCollection( CollectionKey )
															  .WhereEqualsTo( "UserId", userId )
															  .OrderBy( "Created", true )
															  .LimitedTo( limit )
															  .GetDocumentsAsync<Session>();
		List<Session> sessions = [];

		// Build list
		sessions.AddRange( from document in query?.Documents select document.Data );
		
		return sessions;
	}
}

//
