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

namespace Core.Mes.ServerCommon
{
    public interface ILogService
    {
        void WriteLog(DateTime dt, string vLoginID, string vUserName, string vUSERHOSTNAME, string vUSERIPADRESS, string vOPerateType,
          string vControlTYPE, string vOPERATEOBJECT, string vFormName, string vClassName, string vREMARK);
    }

    public class CoreWriteLogFile
    {
        private static object lockObj = new object();


        public static void WriteLog(DateTime dt, string vLoginID, string vUserName, string vUSERHOSTNAME, string vUSERIPADRESS, string vOPerateType,
            string vControlTYPE, string vOPERATEOBJECT, string vFormName, string vClassName, string vREMARK)
        {
            lock (lockObj)
            {
                try
                {
                    string filePath = System.Environment.CurrentDirectory + @"\log\UserEvents\";
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath); 
                    }

                    string logFile = filePath + "UE_" + dt.ToString("yyyyMMdd") + "_LOG" + ".log";
                    FileInfo fi = new FileInfo(logFile);
                    StreamWriter sw = null;
                    try
                    {
                        string sContent = "";
                        if (fi.Exists)
                        {
                            sw = fi.AppendText();
                        }
                        else
                        {
                            sw = fi.CreateText();
                            sContent = string.Format("{10,23}, {0,10}, {1,10}, {2,20}, {3,15}, {4,5}, {5,10}, {6,-10}, [{7}], [{8}], [{9}]", " 登录ID", "用户名", "主机名", "主机IP", "操作类型", "控件类型", "控件名次", "窗口名称", "窗口类型", "备注", "时间");
                            sw.WriteLine(sContent);
                        }

                        sContent = string.Format("{0,10}, {1,10}, {2,20}, {3,15}, {4,5}, {5,10}, {6,-10}, [{7}], [{8}], [{9}]", vLoginID, vUserName, vUSERHOSTNAME, vUSERIPADRESS, vOPerateType, vControlTYPE, vOPERATEOBJECT, vFormName, vClassName, vREMARK);
                        string sc = string.Format("{0}, {1}", dt.ToString("yyyy-MM-dd HH:mm:ss.fff"), sContent);
                        sw.WriteLine(sc.Trim());
                        sw.Flush();
                    }
                    finally
                    {
                        if (sw != null)
                            sw.Close();
                    }
                }
                catch
                {
                    // do nothing.
                }
            }
        }
    }


}
