using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FLY.Thick.Base.IService;
using FLY.Thick.Base.Common;
using System.ComponentModel;

namespace FLY.Thick.Base.Server
{
    public class Password : IPasswordService, Misc.ISaveToXml, INotifyPropertyChanged
    {
        private List<PasswordCell> pws = new List<PasswordCell>();
        /// <summary>
        /// 密码列表。 储存在 服务器
        /// </summary>
        public List<PasswordCell> PWs 
        {
            get {
                return pws;
            }
        }
        private string param_path = "password.xml";
        public Password() 
        {
            

        }
        public Password(string param_path) 
        {
            if (!string.IsNullOrEmpty(param_path))
                this.param_path = param_path;
            Load();
        }
        public AUTHORIZE_RESULT Authorize(string pw, int level)
        {
            return AUTHORIZE_RESULT.OK;
        }

        public void Apply()
        {
            //保证密码都是唯一的!!!
            for (int i = 0; i < PWs.Count(); i++)
            {
                string p = PWs[i].Password;
                List<PasswordCell> pwlist = PWs.FindAll(pw => pw.Password == p);
                if (pwlist.Count > 1) 
                {
                    //有重复,删除第2个
                    PWs.Remove(pwlist[1]);
                }
            }
            Save();
            NotifyPropertyChanged("PWs");
        }
        void Save() 
        {
            Misc.SaveToXmlHepler.Save(param_path, this);
        }

        static Password()
        {
            Misc.SaveToXmlHepler.Regist(typeof(PasswordCell));
        }
        void Load()
        {
            Misc.SaveToXmlHepler.Load(param_path, this);
            if (PWs.Count() == 0)
            {
                PWs.Add(new PasswordCell() { Password = "flymeasure", Level = 10 });
                PWs.Add(new PasswordCell() { Password = "1", Level = 2 });
                Save();
            }
        }
        public string[] GetSavePropertyNames()
        {
            return new string[] { "PWs" };
        }
        #region INotifyPropertyChanged 成员

        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

        protected void NotifyPropertyChanged(string propertyname)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyname));
            }
        }

        #endregion
    }
}