using System;
using System.Diagnostics;
using System.IO;
using System.Text;
 
namespace LogClass
{
    public class LOG
    {
        static public StringBuilder _log = new StringBuilder();
        static FileIO fio;
        static public int min = 0;
        static public int max = 10;
        //
        static LOG()
        {
            fio = new FileIO();
            fio.OpenWriteFile("log.txt");
        }
        static public void error(object str)
        {
            log("Erorr:" + str, 10);
        }
        //static object syn = new object();
        /// <summary>
        /// log写入
        /// </summary>
        /// <param name="str"></param>
        static public void log(object str)
        {
            log(str, 0);
        }
        static public void log(string str)
        {
            log(str, 0);
        }
        /// <summary>
        /// log等级定制
        /// </summary>
        /// <param name="p"></param>
        /// <param name="level"></param>
        public static void log(object p, int level)
        {
            log(p.ToString(), level);
        }

        static public void log(string str, int level)
        {
            if(level < fio.LogLevel)
            {
                return;
            }
            if (str == null)
            {
                str = "null";
            }
            fio.WriteLine(DateTime.Now.ToString("O") + "->" + str + "\r\n");
        }
        /// <summary>
        /// 修改Log的限制等级0日志最多，10最少
        /// </summary>
        /// <param name="Loglevel"></param>
        public static void ChangeLogLevel(int Loglevel)
        {
            fio.LogLevel = Loglevel;
        }



        public static void LogSurPlusMemory()
        {
            PerformanceCounter ramCounter = new PerformanceCounter("Memory", "Available MBytes");
            var ramAvailable = ramCounter.NextValue();
            string ramAvaiableStr = string.Format("{0} MB", ramAvailable);
            log($"剩余物理内存：{ramAvaiableStr}");
        }
    }

    public class FileIO
    {
        private FileStream fsr;
        private FileStream fsw;
        private StreamWriter sw;
        private StreamReader sr;
        private string LogFloderPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Log\\";
        private double LogFileSize =128 * Math.Pow(1024, 3);
        public int LogLevel = 5;
        // 创建用于读取文件行的文件流和StreamWriter对象
        public void OpenReadFile(string file)
        {
            if (!File.Exists(file))
                File.Create(file).Close();
            fsr = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
            sr = new StreamReader(fsr);
        }
        public void Clear()
        {
            CloseWriteFile();
        }
        // 关闭读文件流
        public void CloseReadFile()
        {
            if (fsr != null)
                fsr.Close();
        }
        // 创建用于向文件中追加行的文件流和StreamWriter对象
        public void OpenWriteFile(string file)
        {
            int i = 1;
            while(true)
            {
                if (!Directory.Exists(LogFloderPath))//如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(LogFloderPath);
                }
                if (!File.Exists(LogFloderPath + file))  // 如果文件不存在，先创建这个文件
                    File.Create(LogFloderPath + file).Close();
                // 以追加模式打开这个文件
                fsw = new FileStream(LogFloderPath + file, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
                if (fsw.Length > LogFileSize)
                {
                    file = "log"+ i + ".txt";
                    i++ ;
                    continue;
                }
                break;
            }
            // 根据创建的FileStream对象来创建StreamWriter对象
            sw = new StreamWriter(fsw);
        }
        // 关闭写文件流
        public void CloseWriteFile()
        {
            if (fsw != null)
                fsw.Close();
        }
        // 从文件中读取一行
        public string ReadLine()
        {
            if (sr.EndOfStream)  // 如果文件流指针已经指向文件尾部，返回null
                return null;
            return sr.ReadLine();
        }
        // 向文件中追加一行字符串
        public void WriteLine(string s)
        {
            if(fsw.Length > LogFileSize)
            {
                OpenWriteFile("log.txt");
            }
            lock (sw)
            {
                sw.WriteLine(s);
                sw.Flush(); // 刷新写入缓冲区，使这一行对于读文件流可见
            }
        }
        // 用于判断文件流指针是否位于文件尾部
        public bool IsEof()
        {
            return sr.EndOfStream;
        }
    }
}