using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Timers;
using System.Web;
using System.Xml;
using Wechat;

namespace jiouosdp
{
    /// <summary>
    /// 微信api转发管理类
    /// </summary>
    public class ApiTranAppIdList
    {
        public static Hashtable AppIdList;
        public static Hashtable UserIdList;
        public static string Path;
        static object lockPath = new object();
        static Timer timer;


        public static void Start()
        {
            AppIdList = Hashtable.Synchronized(new Hashtable());
            UserIdList = Hashtable.Synchronized(new Hashtable());

            ReadConfig();

            timer = new Timer(1000 * 60 * 5);
            timer.Elapsed += timer_Elapsed;
            timer.Start();
        }
        static void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            ReadConfig();
        }

        public static void AddConfig(string appid, string userid, string key, string redirect_uri, string iscallauthoevent = "true", string isautoinsert = "false")
        {
            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                try
                {
                    if (timer != null) timer.Start();
                    lock (lockPath)
                    {
                        if (AppIdList.ContainsKey(appid) != true)
                        {
                            if (File.Exists(Path) != true)
                                return;

                            XmlDocument doc = new XmlDocument();
                            doc.Load(Path);

                            XmlNode xn = doc.SelectSingleNode("/merchs");
                            XmlElement element = doc.CreateElement("users");
                            element.SetAttribute("appid", appid);
                            element.SetAttribute("userid", userid);
                            element.SetAttribute("data", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
                            element.SetAttribute("key", key);
                            element.SetAttribute("redirect_uri", redirect_uri);
                            element.SetAttribute("iscallauthoevent", iscallauthoevent);
                            element.SetAttribute("isautoinsert", isautoinsert);
                            xn.AppendChild(element);

                            ApiTranAppIdListModel model = new ApiTranAppIdListModel()
                            {
                                userid = userid,
                                redirect_uri = redirect_uri,
                                appid = appid,
                                iscallauthoevent = Convert.ToBoolean(iscallauthoevent),
                                isautoadd = Convert.ToBoolean(isautoinsert),
                            };

                            try
                            {
                                doc.Save(Path);
                            }
                            catch
                            {
                                System.Threading.Thread.Sleep(2000);
                                doc.Save(Path);
                            }
                            if (AppIdList.ContainsKey(model.appid) != true)
                                AppIdList.Add(model.appid, model);

                            if (UserIdList.ContainsKey(model.userid) != true)
                                UserIdList.Add(model.userid, model);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogManage.Log("添加api转发配置文件:" + ex.Message);
                }
                finally
                {
                    if (timer != null) timer.Stop();
                }
            });
        }

        public static void ReadConfig()
        {
            try
            {
                lock (lockPath)
                {
                    //LogManage.Log("读api转发配置文件");

                    if (File.Exists(Path) != true)
                        return;

                    XmlDocument doc = new XmlDocument();
                    doc.Load(Path);

                    XmlNodeList nodelist = doc.SelectNodes("/merchs/users");
                    AppIdList.Clear();
                    UserIdList.Clear();
                    foreach (XmlNode v in nodelist)
                    {
                        XmlElement element = (XmlElement)v;
                        ApiTranAppIdListModel model = new ApiTranAppIdListModel()
                        {
                            userid = element.Attributes["userid"].Value,
                            redirect_uri = element.Attributes["redirect_uri"].Value,
                            appid = element.Attributes["appid"].Value,
                            iscallauthoevent = Convert.ToBoolean(element.Attributes["iscallauthoevent"].Value),
                            isautoadd = Convert.ToBoolean(element.Attributes["isautoinsert"].Value),
                        };
                        if (AppIdList.ContainsKey(model.appid) != true)
                            AppIdList.Add(model.appid, model);

                        if (UserIdList.ContainsKey(model.userid) != true)
                            UserIdList.Add(model.userid, model);
                    }

                }
            }
            catch (Exception ex)
            {
                LogManage.Log("读api转发配置文件:" + ex.Message);
            }
        }

        public static ApiTranAppIdListModel GetByAppid(string appid)
        {
            lock (lockPath)
            {
                if (AppIdList.ContainsKey(appid) == true)
                {
                    return AppIdList[appid] as ApiTranAppIdListModel;

                }
                else
                {
                    return null;
                }

            }
        }
        public static ApiTranAppIdListModel GetByUserID(string userid)
        {
            lock (lockPath)
            {
                if (UserIdList.ContainsKey(userid) == true)
                {
                    return UserIdList[userid] as ApiTranAppIdListModel;

                }
                else
                {
                    return null;
                }

            }
        }

    }
    public class ApiTranAppIdListModel
    {
        string _apiurl;
        public string redirect_uri
        {
            set
            {
                if (string.IsNullOrEmpty(value) != true && value.EndsWith("/") != true)
                {
                    _apiurl = value + "/";
                }
                else
                {
                    _apiurl = value;
                }
            }
            get
            {
                return _apiurl;
            }
        }
        public bool iscallauthoevent { get; set; }
        public string appid { get; set; }
        public string userid { get; set; }
        public bool isautoadd { get; set; }
    }
}