using System;
using System.Collections.Generic;
using System.Text;
using Core.Mes.IBaseInterface;
using Core.Mes.ServerFrameWork;
using System.Collections;
using System.IO; 

namespace Core.Mes.ServerListener
{
    public class ServerListener : IComponent
    {
        public ServerListener()
        {
        }

        public ReturnObject SyncFiles(ArrayList FileNames, ArrayList FileBytes, ArrayList FileMD5s, ArrayList FileSHA256s)
        {
            if (this.OwnObjects == null) return new ReturnObject(null, 2, "获取监控服务状态失败!");

            MesServerListener msl = (MesServerListener)(((ArrayList)OwnObjects)[0]);
            //if ((msl.Status & 0x1) == 0) return new ReturnObject(null, 3, "监控服务状态已停止，无法同步！");
            msl.Status = ServerListenerStatus.SyncFiles;

            Util.AppListenerLog(string.Format("开始同步主机文件...[{0}]", FileNames.Count));

            string ServerPath = AppDomain.CurrentDomain.BaseDirectory;
            string UpdatePath = Path.Combine(ServerPath, "~update_file");
            if (!(Directory.Exists(UpdatePath)))
            {
                Directory.CreateDirectory(UpdatePath);
            }
            if (FileNames == null || FileNames.Count == 0 || FileBytes == null || FileBytes.Count == 0 ||
                FileMD5s == null || FileMD5s.Count == 0 || FileSHA256s == null || FileSHA256s.Count == 0) return new ReturnObject();
            if (FileNames.Count != FileBytes.Count ||
                FileNames.Count != FileMD5s.Count ||
                FileNames.Count != FileSHA256s.Count)
                return new ReturnObject(null, 1, "传入参数个数不正确！");

            int FileReceived = 0;
            lock (this)
            {
                string fullFileName = "";
                FileStream fs = null;
                for (int idx = 0; idx < FileNames.Count; idx++)
                {
                    string filename = FileNames[idx].ToString();

                    try
                    {
                        fullFileName = Path.Combine(UpdatePath, filename);
                        fs = new FileStream(fullFileName, FileMode.Create, FileAccess.Write);
                        byte[] filecontent = (byte[])(FileBytes[idx]);
                        fs.Write(filecontent, 0, filecontent.GetLength(0));
                        fs.Flush();
                        fs.Close();
                        FileReceived++;
                        Util.AppListenerLog(string.Format("  接收更新文件[{0,3}/{1,-3}]:{2}", idx + 1, FileNames.Count, filename));
                    }
                    catch
                    {
                        File.Delete(fullFileName);
                    }
                    finally
                    {
                        if (fs != null)
                        {
                            fs.Close();
                        }
                    }
                }
            }

            try
            {
                if (FileReceived == FileNames.Count)
                {
                    Util.AppListenerLog("停止MES服务, 开始备份...");
                    Util.ExistCoreMesServer(msl.ServerManager, true);

                    string CurFileName;
                    string UpdateFileName;
                    string BackupedFileName;
                    string BackUpPath = Path.Combine(Path.Combine(ServerPath, "更新前备份"), DateTime.Now.ToString("yyyyMMdd"));
                    if (!Directory.Exists(BackUpPath))
                    {
                        Directory.CreateDirectory(BackUpPath);
                    }

                    foreach (string filename in FileNames)
                    {
                        CurFileName = Path.Combine(ServerPath, filename);
                        UpdateFileName = Path.Combine(UpdatePath, filename);
                        BackupedFileName = Path.Combine(BackUpPath, filename);

                        if (!File.Exists(BackupedFileName) && File.Exists(CurFileName))
                        {
                            File.Move(CurFileName, BackupedFileName);
                        }
                        else if (File.Exists(CurFileName))
                        {
                            File.Delete(CurFileName);
                        }

                        File.Move(UpdateFileName, CurFileName);
                    }
                    Util.AppListenerLog("备份完成，开始启动MES服务...");

                    Util.StartCoreMesServer(msl.ServerManager, 3);
                }
            }
            catch (Exception ex)
            {
                Util.AppListenerLog("同步失败：" + ex.Message);
            }
            finally
            {
                msl.Status = ServerListenerStatus.Start;
            }
            return new ReturnObject(null, 0, "");


        }

    }
}
