using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace tool
{
    /// <summary>
    /// 日志管理
    /// </summary>
    public class LogManager : Singleton<LogManager>
    {
        DateTime time;                      //文件创建时间
        private string logFileExtName;      //日志文件扩展名（文件尾）
        private Encoding logFileEncoding;   //日志文件编码格式
        private string logFileName;         //日志文件名
        private string logPath;             //日志文件路径
        private bool writeLogTime;          //log文件是否写时间
        private bool writeStatus;           //是否写入标志位
        private string logFilePath;         //log文件路径
        private object obj;
        // 将构造函数私有化，防止外部通过new创建
        private LogManager()
        {
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public  void LogManagerInit()
        {
            logFileExtName = "log";             //日志文件扩展名（文件尾）
            logFileEncoding = Encoding.UTF8;    //日志文件编码格式
            logFileName = string.Empty;         //日志文件名
            logPath = "";                       //日志文件路径
            writeLogTime = true;                //log文件是否写时间
            writeStatus = false;                //是否写入标志位
            logFilePath = "log";                //log文件路径(文件夹名称)
            obj = new object();

        }
        /// <summary>
        /// 日志文件路径
        /// </summary>
        public string CreateLogPath()
        {            
            if (logPath == null || logPath == string.Empty || time.ToString("yyyy-MM-dd") != System.DateTime.Now.ToString("yyyy-MM-dd"))
            {
                try
                {
                    time = System.DateTime.Now;
                    //生成当天的logfile路径
                    logPath = System.IO.Path.Combine(logFilePath, time.ToString("yyyy-MM-dd"));
                }
                catch
                {
                    Console.WriteLine("路径合成失败");
                }
            }
            if (!logPath.EndsWith(@"\"))
            {
                //@"\"=="\\"
                logPath += @"\";
            }
            if (!Directory.Exists(logPath))
            {
                try
                {
                    Directory.CreateDirectory(logPath);
                }
                catch
                {
                    Console.WriteLine("创建文件路径失败");
                }
            }
            return logPath;
        }
        /// <summary>
        /// 写日志
        /// </summary>
        public void WriteLog(LogType logType, string logFile, string msg)
        {
            CreateLogPath();
            //互斥锁
            lock (obj)
            {
                try
                {
                    //创建log文件
                    logFileName = string.Format("{0}{1}.{2}", logPath, logType, this.logFileExtName);
                    using (StreamWriter sw = new StreamWriter(logFileName, true, logFileEncoding))//设为true，追加数据到文件中
                    {
                        //是否写时间
                        if (logType == LogType.PROCESS)
                        {
                            writeLogTime = true;
                        }
                        else
                        {
                            writeLogTime = false;
                        }
                        ////sql类型
                        //if (logType == LogType.DATABASE)
                        //{
                        //    writeStatus = true;
                        //}
                        //else
                        //{
                        //    writeStatus = false;
                        //}
                        if (writeLogTime)
                        {
                            sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:") + logFile + ":" + msg);
                        }
                        else
                        {
                            sw.WriteLine(logFile + "" + msg);
                        }
                    }
                }
                catch { }
            }
        }
        /// <summary>
        /// log类型不定
        /// </summary>
        /// <param name="logType"></param>
        /// <param name="logFile"></param>
        /// <param name="msg"></param>
        public void WriteLog(LogType logType, LogFile logFile, string msg)
        {
            this.WriteLog(logType, logFile.ToString(), msg);
        }
        /// <summary>
        /// log类型为null
        /// </summary>
        /// <param name="logType"></param>
        /// <param name="msg"></param>
        public void WriteLog(LogType logType, string msg)
        {
            this.WriteLog(logType, string.Empty, msg);
        }
        /// <summary>
        /// 读日志文件
        /// </summary>
        /// <param name="sqlStatus"></param>
        /// <param name="sqlMsg"></param>
        public List<string> ReadLog()
        {
            List<string> digitList = new List<string>();
            //string date = System.DateTime.Now.ToString("yyyy-MM-dd");
            //string filePath = logAddress + "\\\\" + date + "\\\\" + "CREDENCES.log";？？？？？？？？？？？？？？？？？？？？
            string filePath = logFilePath + "\\\\" + "CREDENCES.log";
            try
            {
                List<string> logLines = null;
                if (File.Exists(filePath))
                {
                    logLines = new List<string>(File.ReadAllLines(filePath));
                    File.Delete(filePath);
                }
                if (logLines != null)
                {
                    for (int i = 0; i < 300; i++)
                    {
                        string logLine = logLines[i];
                        digitList.Add(logLine);
                        logLines.RemoveAt(i);
                    }
                    File.WriteAllLines(filePath, logLines.ToArray());
                }
            }
            catch (Exception e) { Console.WriteLine(e.Message); }
            return digitList;
        }
        public void WriteCredence(string msg)
        {
            lock (obj)
            {
                try
                {
                    //创建log文件
                    string logname = string.Format("{0}.{1}", "CREDENCES", this.logFileExtName);
                    logFileName = logFilePath + "\\" + logname;
                    using (StreamWriter sw = new StreamWriter(logFileName, true, logFileEncoding))
                    {
                        if (msg.Length == 8)
                        {
                            sw.WriteLine(msg);
                        }
                        else
                        {
                            sw.WriteLine("0" + msg);
                        }
                    }
                }
                catch { }
            }
        }



    }
    /// <summary>
    /// log类型
    /// </summary>
    public enum LogFile
    {
        LOG,
        RESET,
        ERROR,
        WARNING,
        INFO,
        ERROR_NUMBERPLATE
    }
    /// <summary>
    /// log文件类型
    /// </summary>
    public enum LogType
    {
        PROCESS,
        CREDENCES
    }

}
