//******************************************************************************************************
//  DeviceOperations.cs - Gbtc
//
//  Copyright © 2026, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the MIT License (MIT), the "License"; you may not use this
//  file except in compliance with the License. You may obtain a copy of the License at:
//
//      http://opensource.org/licenses/MIT
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  01/15/2026 - J. Ritchie Carroll
//       Generated original version of source code.
//
//******************************************************************************************************

using System.Diagnostics;
using Gemstone.Data.Model;

namespace DNP3ConfigLoader.TableOperations;

/// <summary>
/// Provides operations for Device table records.
/// </summary>
public static class DeviceOperations
{
    /// <summary>
    /// Gets or creates a device record by acronym.
    /// </summary>
    public static Device? GetDeviceRecord(
        TableOperations<Device> deviceOps,
        Guid nodeID,
        int? historianID,
        int? protocolID,
        string deviceAcronym,
        string deviceName,
        string connectionString,
        bool enabled)
    {
        try
        {
            // Lookup device record by acronym
            Device? device = deviceOps.QueryRecordWhere("Acronym = {0}", deviceAcronym);

            if (device is not null)
            {
                // If the record exists, check if it matches the provided details
                if (device.NodeID == nodeID &&
                    device.HistorianID == historianID &&
                    device.ProtocolID == protocolID &&
                    device.Name == deviceName &&
                    device.ConnectionString == connectionString)
                {
                    return device;
                }
            }
            else
            {
                device = deviceOps.NewRecord();
                Debug.Assert(device is not null, "Failed to create new Device record.");
            }

            // Update record fields
            device.NodeID = nodeID;
            device.Acronym = deviceAcronym;
            device.Name = deviceName;
            device.HistorianID = historianID;
            device.ProtocolID = protocolID;
            device.ConnectionString = connectionString;
            device.IsConcentrator = false;

            if (device.ID == 0)
            {
                device.Enabled = enabled;
                deviceOps.AddNewRecord(device);

                // Re-query to get database-assigned ID
                device = deviceOps.QueryRecordWhere("Acronym = {0}", deviceAcronym);
            }
            else
            {
                deviceOps.UpdateRecord(device);
            }

            return device;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error occurred while reading or creating Device record for \"{deviceName}\": {ex.Message}");
            return null;
        }
    }
}
