PhoneToolMX/PhoneToolMX.Models/ViewModels/PhoneVM.cs

71 lines
2.4 KiB
C#
Raw Normal View History

2023-10-18 04:55:10 +00:00
using PhoneToolMX.Data;
using System.ComponentModel.DataAnnotations;
using System.Net.NetworkInformation;
namespace PhoneToolMX.Models.ViewModels
{
[CheckExtensions]
public class PhoneVM : IViewModel
{
public int? Id { get; set; }
[Header("MAC Address")]
[Required]
[RegularExpression("(?:[0-9a-fA-F]{2}[-:]?){6}", ErrorMessage = "Must be of the form XX:XX:XX:XX:XX:XX, XX-XX-XX-XX-XX-XX, or XXXXXXXXXXXX")]
public string MacAddress { get; set; }
[Header("Name", Primary = true)]
[Required]
public string FriendlyName { get; set; }
[Required]
public int? Model { get; set; }
public ICollection<int?> Extensions { get; set; }
2023-10-20 21:32:56 +00:00
[AllowNull]
public int? PrimaryExtension { get; set; }
2023-10-18 04:55:10 +00:00
public int MaxExtensions { get; set; }
public IOwnedModel ToEntity(PTMXContext ctx)
{
2023-10-20 21:32:56 +00:00
var exts = Extensions?.Select(x => ctx.Extensions.FirstOrDefault(e => e.Id == x)).ToList();
2023-10-18 04:55:10 +00:00
return new Phone
{
Id = Id,
MacAddress = PhysicalAddress.Parse(MacAddress),
FriendlyName = FriendlyName,
Model = ctx.PhoneModels.FirstOrDefault(p => p.Id == Model)!,
2023-10-20 21:32:56 +00:00
Extensions = exts,
2023-10-18 04:55:10 +00:00
Owners = new List<User>(),
2023-10-20 21:32:56 +00:00
PrimaryExtension = PrimaryExtension != null
? exts?.FirstOrDefault(x => x.Id == PrimaryExtension)
: null,
2023-10-18 04:55:10 +00:00
};
}
public IOwnedModel ToEntity(PTMXContext ctx, IOwnedModel current)
{
var ent = ToEntity(ctx);
ent.Owners = current.Owners;
return ent;
}
public IViewModel FromEntity(IOwnedModel entity)
{
if (entity is not Phone phoneEnt) throw new ArgumentException("entity must be of type Phone");
return new PhoneVM
{
Id = entity.Id,
MacAddress = phoneEnt.MacAddress.ToString(),
FriendlyName = phoneEnt.FriendlyName,
Model = phoneEnt.Model!.Id,
Extensions = phoneEnt.Extensions?.Select(x => x.Id).ToList(),
MaxExtensions = (int)phoneEnt.Model!.MaxExtensions,
2023-10-20 21:32:56 +00:00
PrimaryExtension = phoneEnt.PrimaryExtension?.Id,
2023-10-18 04:55:10 +00:00
};
}
}
}