// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using FloraMultiPlatformFrontend.Presentation.Models;

namespace FloraMultiPlatformFrontend.Data.Entities;

[Table("CachedWarningAlarms")]
public class CachedWarningAlarm
{
    [Key]
    public int Id { get; set; }

    public string MachineCode { get; set; } = string.Empty;

    public int TagId { get; set; }

    public bool IsWarning { get; set; }

    public bool IsGreater { get; set; }

    public bool IsError { get; set; }

    public string NameOfAlarm { get; set; } = string.Empty;

    public string WarningDescription { get; set; } = string.Empty;

    public int DurationInSeconds { get; set; }

    public int NrOfTimesOccured { get; set; }

    public DateTime QueryStartDate { get; set; }

    public DateTime QueryEndDate { get; set; }

    public DateTime CreatedAt { get; set; }

    public WarningAlarm ToWarningAlarm()
    {
        return new WarningAlarm
        {
            SensorId = this.TagId,
            NameOfAlarm = this.NameOfAlarm,
            WarningDescription = this.WarningDescription,
            DurationInSeconds = this.DurationInSeconds,
            NrOfTimesOccured = this.NrOfTimesOccured,
            Metadata = new WarningAlarm.AlarmMetadata
            {
                IsWarning = this.IsWarning,
                IsGreater = this.IsGreater,
                IsError = this.IsError
            }
        };
    }

    public static CachedWarningAlarm FromWarningAlarm(WarningAlarm wa, string machineCode, DateTime start, DateTime end)
    {
        return new CachedWarningAlarm
        {
            MachineCode = machineCode,
            TagId = wa.SensorId,
            IsWarning = wa.Metadata.IsWarning,
            IsGreater = wa.Metadata.IsGreater,
            IsError = wa.Metadata.IsError,
            NameOfAlarm = wa.NameOfAlarm,
            WarningDescription = wa.WarningDescription,
            DurationInSeconds = wa.DurationInSeconds,
            NrOfTimesOccured = wa.NrOfTimesOccured,
            QueryStartDate = start,
            QueryEndDate = end,
            CreatedAt = DateTime.UtcNow
        };
    }
}
