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 Extensions { get; set; } [AllowNull] public int? PrimaryExtension { get; set; } public int MaxExtensions { get; set; } public IOwnedModel ToEntity(PTMXContext ctx) { var exts = Extensions?.Select(x => ctx.Extensions.FirstOrDefault(e => e.Id == x)).ToList(); return new Phone { Id = Id, MacAddress = PhysicalAddress.Parse(MacAddress), FriendlyName = FriendlyName, Model = ctx.PhoneModels.FirstOrDefault(p => p.Id == Model)!, Extensions = exts, Owners = new List(), PrimaryExtension = PrimaryExtension != null ? exts?.FirstOrDefault(x => x.Id == PrimaryExtension) : null, }; } 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, PrimaryExtension = phoneEnt.PrimaryExtension?.Id, }; } } }