using HslCommunication.LogNet;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProjectManagementSystem.Common.Logger
{
    public class CLog
    {
        public event Action<int, string> OnLog;

        private static string currDir;
        private static CLog m_cLog = new CLog();
        private ConcurrentDictionary<string, ILogNet> m_logDictionary = new ConcurrentDictionary<string, ILogNet>();

        public static CLog Instance
        {
            get { return m_cLog; }
        }

        public string LogDir { get { return currDir; } }
        public ILogNet SystemLog { get { return GetLog("System"); } }
        public ILogNet TaskLog { get { return GetLog("Task"); } }
        public ILogNet DeviceLog { get { return GetLog("Device"); } }

        private CLog()
        {
            string s = System.Reflection.Assembly.GetExecutingAssembly().Location;
            FileInfo finfo = new FileInfo(s);

            string currPath = finfo.DirectoryName;
            currDir = Path.Combine(currPath, "PMS", "Log");

            DirectoryInfo dir = new DirectoryInfo(currDir);
            if (!dir.Exists)
            {
                dir.Create();
            }
        }

        public ILogNet GetLog(string file)
        {
            if (!m_logDictionary.ContainsKey(file))
            {
                string filePath = Path.Combine(currDir, file);
                var logNet = new LogNetDateTime(filePath, GenerateMode.ByEveryDay, 15);
                logNet.SetMessageDegree(HslMessageDegree.DEBUG);
                logNet.BeforeSaveToFile += LogNet_BeforeSaveToFile;

                m_logDictionary.AddOrUpdate(file, logNet, (key, value) => logNet);
            }

            return m_logDictionary[file];
        }

        //public ILogNet GetLog(EnumLogDir logDir)
        //{
        //    return GetLog(logDir.ToString());
        //}
        public ILogNet GetAgvLog(int agvId)
        {
            if (agvId > 0)
            {
                return GetLog($"AGV{agvId}");
            }
            return TaskLog;
        }

        private void LogNet_BeforeSaveToFile(object sender, HslEventArgs e)
        {
            if (OnLog != null)
            {
                OnLog((int)e.HslMessage.Degree, e.HslMessage.ToString());
            }
        }
    }

    public enum EnumLogDir
    {
        System,
    }
}
