using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using QMAPP.FJC.Entity.FileCopy;

namespace ProcessFileSyncService.FileSynchronizers
{
    public class EngelInjectionFileSynchronizer:FileSynchronizer
    {
        string _File_Copy_Path = "C:\\";
        System.Threading.Timer timer;
        public EngelInjectionFileSynchronizer(QMAPP.FJC.Entity.Basic.MachineInfo machien)
            : base(machien)
        {
            _File_Copy_Path = System.Configuration.ConfigurationManager.AppSettings["File_Copy_Path"];
            if (!string.IsNullOrWhiteSpace(System.Configuration.ConfigurationManager.AppSettings["File_Copy_Path_" + this.Machine.MACHINECODDE]))
            {
                _File_Copy_Path = System.Configuration.ConfigurationManager.AppSettings["File_Copy_Path_" + this.Machine.MACHINECODDE];
            }
            timer = new System.Threading.Timer(new System.Threading.TimerCallback(Tick));
        }

        private void Tick(object obj)
        {
            try
            {
                StringBuilder sql = new StringBuilder();
                using (IdentityScope idscope = new IdentityScope(this.Machine.USERNAME, this.Machine.IPADDRESS, this.Machine.PASSWORD))
                {
                    if (!System.IO.File.Exists(this.Machine.EQUIPMENT_DIRECTORY))
                    {
                        return;
                    }
                    System.IO.FileInfo file = new System.IO.FileInfo(this.Machine.EQUIPMENT_DIRECTORY);
                    string filecopy = string.Format("{0}\\{1}", _File_Copy_Path.TrimEnd('\\'), file.Name);
                    if (System.IO.File.Exists(filecopy))
                    {
                        System.IO.File.Delete(filecopy);
                    }
                    file.MoveTo(filecopy);
                    using (System.IO.StreamReader sreader = new System.IO.StreamReader(filecopy, System.Text.Encoding.UTF8))
                    {
                        Console.WriteLine(string.Format("{3:HH:mm:ss}:{0}({1}) {2} ReadFile {4}", this.Machine.MACHINENAME, this.Machine.MACHINECODDE, this.GetType().Name, DateTime.Now, file.Name));
                        string header = "";
                        while (!sreader.EndOfStream)
                        {
                            var line = sreader.ReadLine();
                            if (line.StartsWith("DATE,TIME,COUNT,"))
                            {
                                header = line;
                            }
                            else
                            {
                                if (!string.IsNullOrWhiteSpace(header))
                                {
                                    Console.WriteLine(line);
                                    sql.AppendFormat("INSERT INTO [T_PA_{0}]VALUES(NEWID(),'','','','','{1}','{0}','',GETDATE(),GETDATE(),'{2}','{3}')", this.Machine.MACHINECODDE, this.Machine.MACHINENAME, header, line);
                                    sql.AppendLine("");
                                    //sql.AppendLine("GO");
                                }
                            }
                        }
                    }
                }
                if (sql.Length > 0)
                {
                    using (var session = QMFrameWork.Data.AppDataFactory.CreateMainSession())
                    {
                        session.ExecuteSql(sql.ToString());
                    }
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(string.Format("{3:HH:mm:ss}:{0}({1}) {2} Exception ------------------------- \r\n {4} \r\n---------------------End", this.Machine.MACHINENAME, this.Machine.MACHINECODDE, this.GetType().Name, DateTime.Now, ex.Message));
                
                QMFrameWork.Log.LogManager.LogHelper.Error(
                new QMFrameWork.Log.LogInfo { ErrorInfo = ex, Info = ex.Message });
            }
            finally
            {
                if (timer != null)
                {
                    timer.Change(10000, System.Threading.Timeout.Infinite);
                }
            }
        }

        public override void Start()
        {
            if (timer != null)
            {
                timer.Change(10000, System.Threading.Timeout.Infinite);
            }
            base.Start();
        }

        public override void Stop()
        {
            if (timer != null)
            {
                timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
            }
            base.Stop();
        }

        public override void Dispose()
        {
            if (timer != null)
            {
                timer.Dispose();
                timer = null;
            }
            base.Dispose();
        }
    }
}