using System;
using System.Xml.Linq;
using Sicentury.Core;

namespace MECF.Framework.Common.Account.Permissions;

public sealed class PermissionControlItem : BindableBase, ICloneable
    {
        #region Variables
        
        private string _permissionId;
        private string _name;
        private string _description;
        private PermissionMappedType _myPermission;
        private PermissionMappedType _previousPermission;

        #endregion

        #region Construcors

        public PermissionControlItem(string name, PermissionMappedType permission, string id = "", string description = "")
        {
            _permissionId = id;
            _name = name;
            _description = description;
            _myPermission = permission;
            _previousPermission = permission;
        }

        #endregion

        #region Properties

        /// <summary>
        /// 返回当前权限是否发生了变化。
        /// </summary>
        public bool IsChanged => _myPermission != _previousPermission;

        public string ID
        {
            get => _permissionId;
            set => Set(ref _permissionId, value);
        }
        
        public PermissionMappedType Permission
        {
            get => _myPermission;
            set
            {
                _myPermission = value;
                OnPropertyChanged();
                OnPropertyChanged(nameof(IsChanged));
            }
        }
        

        public string Name
        {
            get => _name;
            set => Set(ref _name, value);
        }
        
        public string Description
        {
            get => _description;
            set => Set(ref _description, value);
        }
        
        #endregion

        #region Methods

        public object Clone()
        {
            return new PermissionControlItem(Name, Permission, ID, Description);
        }

        public void Update()
        {
            _previousPermission = _myPermission;
        }

        /// <summary>
        /// 从当前对象创建XElement对象。
        /// </summary>
        /// <returns></returns>
        public XElement ToXElement()
        {
            var xe = new XElement("Perm",
                new XAttribute("name", Name),
                new XAttribute("id", ID),
                new XAttribute("perm", Permission.EnumValue),
                new XAttribute("description", Description));
            return xe;
        }

        /// <inheritdoc />
        public override string ToString()
        {
            return $"{Name}, {Permission}, Changed: {IsChanged}";
        }

        #endregion

    }