using BarContracts.BindingModels;
using BarContracts.ViewModels;
using BarDataModels.Models;
using System.Xml.Linq;

namespace BarFileImplement.Models
{
    public class Component : IComponentModel
    {
        public int Id { get; private set; }

        public string ComponentName { get; private set; } = string.Empty;

        public double Cost { get; set; }

        public static Component? Create(ComponentBindingModel Model)
        {
            if (Model is null)
                return null;

            return new Component()
            {
                Id = Model.Id,
                ComponentName = Model.ComponentName,
                Cost = Model.Cost
            };
        }

        public static Component? Create(XElement Element)
        {
            if (Element is null)
                return null;

            return new Component()
            {
                Id = Convert.ToInt32(Element.Attribute("Id")!.Value),
                ComponentName = Element.Element("ComponentName")!.Value,
                Cost = Convert.ToDouble(Element.Element("Cost")!.Value)
            };
        }

        public void Update(ComponentBindingModel Model)
        {
            if (Model is null)
                return;

            ComponentName = Model.ComponentName;
            Cost = Model.Cost;
        }

        public ComponentViewModel GetViewModel => new()
        {
            Id = Id,
            ComponentName = ComponentName,
            Cost = Cost
        };

        public XElement GetXElement => new(
            "Component",
            new XAttribute("Id", Id),
            new XElement("ComponentName", ComponentName),
            new XElement("Cost", Cost.ToString())
        );
    }
}
