using FLY.OBJComponents.Client;
using FLY.OBJComponents.IService;
using FLY.Thick.Base.Common;
using FLY.Thick.Base.IService;
using FObjBase;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FLY.Thick.Base.UI
{

    public class PasswordAuthorize:INotifyPropertyChanged
    {
        const string JSONDIST_KEY = "password";
        IJsonDistService jsonDist;
        /// <summary>
        /// 数据库
        /// </summary>
        [PropertyChanged.DoNotCheckEquality]
        public PasswordJsonDb Db { get; private set; } = new PasswordJsonDb();
        /// <summary>
        /// 修改时间
        /// </summary>
        public DateTime Time { get; set; }

        public PasswordAuthorize(IJsonDistService jsonDist)
        {
            this.jsonDist = jsonDist;
            Load();
            if (jsonDist is FObjServiceClient)
            {
                var objServiceClient = jsonDist as FObjServiceClient;
                if (objServiceClient.IsConnected)
                {
                    //连接成功
                    fetch_db();
                }
                objServiceClient.PropertyChanged += ObjServiceClient_PropertyChanged;
            }
            else 
            {
                //运行在服务器，之间获取数据
                fetch_db();
            }

            jsonDist.ValueChanged += JsonDist_ValueChanged;

        }

        private void ObjServiceClient_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "IsConnected") 
            {
                var objServiceClient = sender as FObjServiceClient;
                if (objServiceClient.IsConnected)
                {
                    //连接成功
                    fetch_db();
                }
            }
        }

        private void JsonDist_ValueChanged(object sender, JsonDistValueValueChangedEventArgs e)
        {
            if (e.key == JSONDIST_KEY) 
            {
                fetch_db();
            }
        }

        /// <summary>
        /// 设置默认数据
        /// </summary>
        void default_db()
        {
            Time = DateTime.MinValue;
            Db = new PasswordJsonDb()
            {
                Pws = new List<PasswordCell>{
                    new PasswordCell(){Level = 10, Password = "flymeasure"},
                    new PasswordCell(){Level = 1, Password = "1"}
                },
                UiLvs = new List<UiLvCell>()
            };
        }
        /// <summary>
        /// 从服务器获取数据
        /// </summary>
        void fetch_db() 
        {
            //连接成功
            this.jsonDist.GetValue(JSONDIST_KEY, (asyncContext, retData) =>
            {
                if (retData == null)
                {
                    //没有数据
                    //放入默认值
                    push_db(Db);
                }
                else 
                {
                    var distCell = (DistCell)retData;
                    var p = (distCell.Value).ToObject<PasswordJsonDb>();
                    if (p == null || p.Pws==null || p.Pws.Count()==0)//异常
                    {
                        push_db(Db);
                    }
                    else 
                    {
                        if (Time != distCell.Time) 
                        {
                            Db = p;
                            Save();
                            Time = distCell.Time;
                        }
                    }
                }
            }, this);
        }
        /// <summary>
        /// 推送数据到服务器
        /// </summary>
        void push_db(PasswordJsonDb db) 
        {
            this.jsonDist.SetValue(JSONDIST_KEY, JObject.FromObject(db));
        }
        /// <summary>
        /// 输入密码，确认密码权限是否满足要求， level越大，要求权限越大
        /// </summary>
        /// <param name="pw"></param>
        /// <param name="level"></param>
        /// <returns></returns>
        public AUTHORIZE_RESULT Authorize(string pw, int level)
        {
            if (level <= 0)
                return AUTHORIZE_RESULT.OK;

            var v = from p in Db.Pws where p.Password == pw select p;
            if (v.Count() > 0)
            {
                if (v.First().Level >= level)
                    return AUTHORIZE_RESULT.OK;
                else
                    return AUTHORIZE_RESULT.ERR_LEVEL;
            }
            return AUTHORIZE_RESULT.ERR_PW;
        }
        /// <summary>
        /// 输入密码，确认密码权限是否满足要求， level越大，要求权限越大
        /// </summary>
        /// <param name="pw"></param>
        /// <param name="uiName">界面名称</param>
        /// <returns></returns>
        public AUTHORIZE_RESULT Authorize(string pw, string uiName) 
        {
            return Authorize(pw, GetLv(uiName));
        }
        /// <summary>
        /// 获取授权级别， 0级不需要密码就能通过
        /// </summary>
        /// <param name="uiName"></param>
        /// <returns></returns>
        public int GetLv(string uiName) 
        {
            Base.Common.UiLvCell uiLvCell;

            if (Db.UiLvs == null)
            {
                Db.UiLvs = new List<Base.Common.UiLvCell>();
                uiLvCell = new Base.Common.UiLvCell()
                {
                    UiName = uiName
                };

                //没有，添加
                Db.UiLvs.Add(uiLvCell);

            }
            else
            {
                uiLvCell = Db.UiLvs.Find(c => c.UiName == uiName);
                if (uiLvCell == null)
                {
                    uiLvCell = new Base.Common.UiLvCell()
                    {
                        UiName = uiName
                    };

                    //没有，添加
                    Db.UiLvs.Add(uiLvCell);
                }
            }
            return uiLvCell.Level;
        }

        string file_path = "password.json";

        public event PropertyChangedEventHandler PropertyChanged;

        public void Apply(PasswordJsonDb db) 
        {
            push_db(db);
        }
        void Save()
        {
            PasswordJsonDb2 p = new PasswordJsonDb2
            {
                Db = Db,
                Time = Time
            };
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(p);
            try
            {
                File.WriteAllText(file_path, json);
            }
            catch
            {

            }
        }

        void Load()
        {
            if (!File.Exists(file_path))
            {
                default_db();
                return;
            }

            string json = File.ReadAllText("password.json");
            try
            {
                var p = Newtonsoft.Json.JsonConvert.DeserializeObject<PasswordJsonDb2>(json);
                Db = p.Db;
                Time = p.Time;
            }
            catch {
            
            }
            if (Db == null || Db.Pws == null || Db.Pws.Count()==0) //异常
            {
                default_db();
            }
        }
    }

    /// <summary>
    /// 授权输入返回结果
    /// </summary>
    public enum AUTHORIZE_RESULT
    {
        /// <summary>
        /// 成功
        /// </summary>
        OK,
        /// <summary>
        /// 不够级别
        /// </summary>
        ERR_LEVEL,
        /// <summary>
        /// 密码出错
        /// </summary>
        ERR_PW
    }


    public class PasswordJsonDb2
    {
        public PasswordJsonDb Db;
        /// <summary>
        /// 修改时间
        /// </summary>
        public DateTime Time;

    }
    public class PasswordJsonDb
    {
        /// <summary>
        /// 界面授权列表
        /// </summary>
        public List<UiLvCell> UiLvs;

        /// <summary>
        /// 密码列表
        /// </summary>
        public List<PasswordCell> Pws;
    }

}
