using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Configuration;
using System.Threading;
namespace WcfControlMonitorLib

{
    /// <summary>
    /// 所有进制之间的转换函数库
    /// Creator:Richard.liu
    /// </summary>
    public static  class CCarryConvert
    {
        static StringBuilder filePath = new StringBuilder();
        static StringBuilder returnstr = new StringBuilder();
        static StringBuilder strf = new StringBuilder();
        static StringBuilder filepath1 = new StringBuilder();
        static StringBuilder mydate = new StringBuilder();
        static StringBuilder path1= new StringBuilder();
        static StringBuilder pathnew= new StringBuilder();
        static string[] files; 
        static string[] doc = new string[3] { "DarkCasket", "ReceiveAGVDarkCasket", "LoginDarkCasket" };
        /// <summary>
        /// 十进制转二进制
        /// </summary>
        /// <param name="dec">十进制数</param>
        /// <returns>二进制字符串</returns>
        //public static string DecimalToBin(decimal dec)
        //{
        //     return Convert.ToString(dec, 2);
        //}
        /// <summary>
        /// 十进制转十六进制
        /// </summary>
        /// <param name="dec">十进制数</param>
        /// <returns>十六进制字符串</returns>
        public static string DecimalToHex(byte dec)
        {
            return Convert.ToString(dec, 16);
        }
        /// <summary>
        /// 十进制转十六进制
        /// </summary>
        /// <param name="dec"></param>
        /// <returns></returns>
        public static string DecimalToHex(int dec)
        {
            return Convert.ToString(dec, 16);
        }
        /// <summary>
        /// 十进制转八进制
        /// </summary>
        /// <param name="dec">十进制数</param>
        /// <returns>八进制字符串</returns>
        public static string DecimalToOct(byte  dec)
        {
            return Convert.ToString(dec, 8);
        }
        /// <summary>
        /// 二进制转十进制
        /// </summary>
        /// <param name="bin">二进制字符串</param>
        /// <returns>十进制数</returns>
        public static Int32 BinToDecimal(string bin)
        {
           return  Convert.ToInt32(bin, 2);
        }
        /// <summary>
        /// 八进制转十进制
        /// </summary>
        /// <param name="bin">八进制字符串</param>
        /// <returns>十进制数</returns>
        public static Int32 OctToDecimal(string Oct)
        {
           return  Convert.ToInt32(Oct , 8);
        }

        /// <summary>
        /// 十六进制转十进制
        /// </summary>
        /// <param name="bin">十六进制字符串</param>
        /// <returns>十进制数</returns>
        public static Int32 HexToDecimal(string hex)
        {
           return  Convert.ToInt32(hex , 16);
        }
        /// <summary>
        /// 十六进制转字节型十进制
        /// </summary>
        /// <param name="bin">十六进制字符串</param>
        /// <returns>字节型十进制数</returns>
        public static byte HexToByte(string hex)
        {
            return Convert.ToByte(hex, 16);
        }
       /// <summary>
        /// 在十进制数获得指定bit位的二进制字符:0/1
       /// </summary>
        /// <param name="Int">十进制数</param>
       /// <param name="bitno">比特位</param>
       /// <returns></returns>
        public static byte GetBitFromInteger(int Int, int bitno)
        {
            
            if ((Int & Convert.ToInt32(Math.Pow(2, Convert.ToDouble(bitno)))) == Convert.ToInt32(Math.Pow(2, Convert.ToDouble(bitno))))
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
        /// <summary>
        /// byte[0]存放高八位,byte[1]存放低八位
        /// </summary>
        /// <param name="_int16"></param>
        /// <returns></returns>
        public static byte[] GetByteFromInt16(int _int16)
        {
            char[] cc = new char[1] { '.' };
            string[] sp;
            byte[] _bytes = new byte[2];
            sp = Convert.ToString(_int16 >> 8).Split(cc);
            _bytes[0] =Convert.ToByte( sp[0]);
            _bytes[1] =Convert.ToByte( _int16 & 255);
            return _bytes;
        }
        public static UInt16  GetInt16FromBytes(byte[] _bytes)
        {
            UInt16 _int16;
            _int16 =Convert.ToUInt16( _bytes[1] +( _bytes[0]*256));
            return _int16;
        }
        /// <summary>
        /// 读取某一天的通讯日志,就是所谓的黑匣子
        /// </summary>
        /// <param name="mydate">指定的日期</param>
        /// <returns>这一天的所有通讯记录</returns>
        public static string  ReadCommLog(string mydate)
        {
            filePath.Remove(0, filePath.Length);
            filePath.Append(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().GetName().ToString()))).Append("\\").Append(mydate + ".log");
            StreamReader sr = new StreamReader(filePath.ToString());
            if (sr.EndOfStream == false)
            {
                returnstr.Remove(0, returnstr.Length);
                returnstr.Append(sr.ReadToEnd());
                sr.Close();
                return returnstr.ToString();
            }
            else
            {
                sr.Close();
                return "";
            }
            
        }
        /// <summary>
        /// 写黑匣子
        /// </summary>
        /// <param name="mydate"></param>
        /// <param name="textline"></param>
        /// <returns></returns>
        public static bool WriteCommLog(string mydate, string textline)
        {
            try
            {
                //20110412
                mydate = DateTime.Parse(mydate).Date.ToString("u");
                mydate = mydate.Substring(0,10);

                filePath.Remove(0, filePath.Length);
                filePath.Append(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().GetName().ToString()))).Append("\\").Append("DarkCasket").Append("\\");
               
                if (Directory.Exists(filePath.ToString()) == false)
                {
                    Directory.CreateDirectory(filePath.ToString());
                }
                //1--99循环
                
                for (int fcount = 1; fcount <= 99; fcount++)
                {
                    strf.Remove(0, strf.Length);
                    if (fcount.ToString().Length < 2)
                    {
                        strf .Append( "0" ).Append( fcount.ToString());
                    }
                    else
                    {
                        strf .Append( fcount.ToString());
                    }

                    filepath1.Remove(0, filepath1.Length);
                    filepath1.Append(filePath.ToString()).Append(mydate).Append(strf).Append(".log");
                    if (File.Exists(filepath1.ToString()) == false)
                    {
                        
                       
                        using (StreamWriter sw = File.CreateText(filepath1.ToString()))
                        {
                            sw.WriteLine("通讯时间**********接口类型**********命令**********地址/端口**********报文内容");
                            sw.WriteLine(textline);
                            //20091102
                            sw.Close();
                            sw.Dispose();
                        }//
                        
                        return true;//20081217
                    }
                    else
                    {
                        FileInfo ff = new FileInfo(filepath1.ToString());
                        AppSettingsReader asr = new AppSettingsReader();
                        long len = (long)asr.GetValue("DarkCasketSize", typeof(long));
                        if (ff.Length > len)
                        {
                            continue;
                            
                        }
                        else
                        {

                            
                            using (StreamWriter sw = File.AppendText(filepath1.ToString()))
                            {

                                sw.WriteLine(textline);
                                //20091102
                                sw.Close();
                                sw.Dispose();
                                
                            }
                            
                            return true;//20081217
                            
                        }
                        
                    }
                }
                //20081217
                //99个文件都写满了,删除今天的99个文件重新开始
                for (int fcount = 1; fcount <= 99; fcount++)
                {
                    strf.Remove(0, strf.Length);
                    if (fcount.ToString().Length < 2)
                    {
                        
                        strf .Append( "0" ).Append( fcount.ToString());
                    }
                    else
                    {
                        strf .Append( fcount.ToString());
                    }

                    filepath1.Remove(0, filepath1.Length);
                    filepath1 .Append(filePath).Append( mydate ).Append( strf ).Append( ".log");
                    if (File.Exists(filepath1.ToString()) == true)
                    {
                        File.Delete(filepath1.ToString());
                    }
                }
                filepath1.Remove(0, filepath1.Length);
                filepath1.Append(filePath).Append( mydate ).Append( "01.log");
                
                {
                    
                    using (StreamWriter sw = File.CreateText(filepath1.ToString()))
                    {
                        sw.WriteLine("通讯时间**********接口类型**********命令**********地址/端口**********报文内容");
                        sw.WriteLine(textline);
                        //20091102
                        sw.Close();
                        sw.Dispose();
                    }
                   
                }
                return true; 
            }
            catch //(Exception ex)
                {
                   
                    return false;
                    //throw ex;
                }

        }
        public static bool WriteCommLog(string DarkCasketFolder, string mydate, string textline)
        {
            try
            {
                //20110412
                mydate=DateTime.Parse(mydate).ToString("u");
                mydate=mydate.Substring(0,10);


                filePath.Remove(0, filePath.Length);
                filePath.Append(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().GetName().ToString()))).Append("\\");

                filePath.Append(DarkCasketFolder).Append("DarkCasket").Append("\\");
                if (Directory.Exists(filePath.ToString()) == false)
                {
                    Directory.CreateDirectory(filePath.ToString());
                }
                //1--99循环
                
                for (int fcount = 1; fcount <= 99; fcount++)
                {
                    strf.Remove(0, strf.Length);
                    if (fcount.ToString().Length < 2)
                    {
                        strf .Append("0" ).Append( fcount.ToString());
                    }
                    else
                    {
                        strf .Append( fcount.ToString());
                    }

                    filepath1.Remove(0, filepath1.Length);
                    filepath1 .Append( filePath).Append( mydate).Append( strf).Append( ".log");
                    if (File.Exists(filepath1.ToString()) == false)
                    {
                        
                        using (StreamWriter sw = File.CreateText(filepath1.ToString()))
                        {
                            sw.WriteLine("通讯时间**********接口类型**********命令**********地址/端口**********报文内容");
                            sw.WriteLine(textline);
                            //20091102
                            sw.Close();
                            sw.Dispose();
                        }//
                        
                        
                        return true;//20081217
                    }
                    else
                    {
                        FileInfo ff = new FileInfo(filepath1.ToString());
                        AppSettingsReader asr = new AppSettingsReader();
                        long len = (long)asr.GetValue("DarkCasketSize", typeof(long));
                        if (ff.Length > len)
                        {
                            continue;

                        }
                        else
                        {
                            
                            
                            using (StreamWriter sw = File.AppendText(filepath1.ToString()))
                            {

                                sw.WriteLine(textline);
                                //20091102
                                sw.Close();
                                sw.Dispose();
                            }
                            
                            
                            return true;//20081217
                            
                        }
                    }
                }
                //20081217
                //99个文件都写满了,删除今天的99个文件重新开始
                for (int fcount = 1; fcount <= 99; fcount++)
                {
                    strf.Remove(0, strf.Length);
                    if (fcount.ToString().Length < 2)
                    {
                        strf .Append( "0" ).Append( fcount.ToString());
                    }
                    else
                    {
                        strf .Append( fcount.ToString());
                    }

                    filepath1.Remove(0, filepath1.Length);
                    filepath1 .Append(filePath).Append( mydate).Append( strf ).Append( ".log");
                    if (File.Exists(filepath1.ToString()) == true)
                    {
                        File.Delete(filepath1.ToString());
                    }
                }
                filepath1.Remove(0, filepath1.Length);
                filepath1 .Append( filePath).Append(mydate).Append( "01.log");
                
                {
                    
                    using (StreamWriter sw = File.CreateText(filepath1.ToString()))
                    {
                        sw.WriteLine("通讯时间**********接口类型**********命令**********地址/端口**********报文内容");
                        sw.WriteLine(textline);
                        //20091102
                        sw.Close();
                        sw.Dispose();
                    }
                    
                }
                return true;
            }
            catch //(Exception ex)
            {
                
                return false;
                //throw ex;
            }

        }
       
        
        public static void WriteDarkCasket(string DarkCasketFolder, string interfacename, string ordername, string addr_port, byte[] message)
        {
            strf.Remove(0, strf.Length);
            if (message != null)
            {
             
                for (int i = 0; i < message.GetLength(0); i++)
                {
                    strf.Append( "-" ).Append( message[i].ToString());
                }
            }
            returnstr.Remove(0, returnstr.Length);
            returnstr.Append(DateTime.Now.ToLongTimeString()).Append(":").Append(DateTime.Now.Millisecond).Append("**").Append(interfacename).Append("**").Append(ordername).Append("**").Append(addr_port).Append("**").Append(strf);
            CCarryConvert.WriteCommLog(DarkCasketFolder, DateTime.Today.ToShortDateString(), returnstr.ToString());

        }
        public static void WriteDarkCasket(string DarkCasketFolder, string interfacename, string ordername, string addr_port, int[] message)
        {
            strf.Remove(0, strf.Length);
            if (message!= null)
            {
                
                for (int i = 0; i < message.GetLength(0); i++)
                {
                    strf .Append("-").Append( message[i].ToString());
                }
            }
            returnstr.Remove(0, returnstr.Length);
            returnstr.Append(DateTime.Now.ToLongTimeString()).Append(":").Append(DateTime.Now.Millisecond).Append("**").Append(interfacename).Append("**").Append(ordername).Append("**").Append(addr_port).Append("**").Append(strf);
            CCarryConvert.WriteCommLog(DarkCasketFolder, DateTime.Today.ToShortDateString(), returnstr.ToString());

        }
        /// <summary>
        /// 写黑匣子
        /// </summary>
        /// <param name="interfacename"></param>
        /// <param name="ordername"></param>
        /// <param name="addr_port"></param>
        /// <param name="message"></param>
        public static void WriteDarkCasket(string interfacename, string ordername, string addr_port, string message)
        {

            returnstr.Remove(0, returnstr.Length);
            returnstr.Append(DateTime.Now.ToLongTimeString()).Append(":").Append(DateTime.Now.Millisecond).Append("**").Append(interfacename).Append("**").Append(ordername).Append("**").Append(addr_port).Append("**").Append(message);
            CCarryConvert.WriteCommLog(DateTime.Today.ToShortDateString(), returnstr.ToString());

        }
        public static void WriteDarkCasket(string DarkCasketFolder, string interfacename, string ordername, string addr_port, string message)
        {


            returnstr.Remove(0, returnstr.Length);
            returnstr.Append(DateTime.Now.ToLongTimeString()).Append(":").Append(DateTime.Now.Millisecond).Append("**").Append(interfacename).Append("**").Append(ordername).Append("**").Append(addr_port).Append("**").Append(message);
            CCarryConvert.WriteCommLog(DarkCasketFolder, DateTime.Today.ToShortDateString(), returnstr.ToString());

        }
        /// <summary>
        /// 执行整理黑匣子文件;在app.config文件中找到整理周期
        /// </summary>
        public static void NeatenDarkCasket()
        {
            try
            {
                
               
                
                AppSettingsReader asr = new AppSettingsReader();
                long FileSum = (long)asr.GetValue("DarkCasketSum", typeof(long));

                for (int ii = doc.GetLowerBound(0); ii <= doc.GetUpperBound(0); ii++)
                {
                    filePath.Remove(0, filePath.Length);
                    filePath.Append(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().GetName().ToString()))).Append(doc[ii]);
                   

                    if (Directory.Exists(filePath.ToString()) == false) continue;

                    files = Directory.GetFiles(filePath.ToString());
                    Array.Sort(files);//20100521
                    int fc = files.GetLength(0);
                    //string strf = string.Empty;
                    if ((fc - FileSum) < 1) continue;//20100521
                    for (long fi = 0; fi <= (fc - FileSum - 1); fi++)//20100521
                    {
                        File.Delete(files[fi]);
                    }
                    

                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        

    }
}