using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.IO;
using System.Text;
using System.Windows.Forms;

using SmartX;

using ITC81DB.Forms;
using ITC81DB.DialogForms;
using ITC81DB_ImageDll;

namespace ITC81DB.Controls
{
    public partial class ControlCenterEquipSystemLog : UserControl
    {
        #region Field
        private FormMenu m_ParentForm;
        private int FileIndex;
        #endregion

        #region Constructor
        public ControlCenterEquipSystemLog(FormMenu parent)
        {
            InitializeComponent();

            this.ParentForm = parent;

            this.InitializeDesign();
            this.DefaultSetting();
        }
        #endregion

        #region Property
        public FormMenu ParentForm
        {
            get { return this.m_ParentForm; }
            private set { this.m_ParentForm = value; }
        }
        #endregion

        #region Method
        public void InitializeDesign()
        {
            if (this.ParentForm.ParentForm.SystemConfig1.Language == DataStore.LanguageID.English)
            {
                this.labelTitleFileList.Text = "File List";
            }
            else if (this.ParentForm.ParentForm.SystemConfig1.Language == DataStore.LanguageID.Chinese)
            {
                this.labelTitleFileList.Text = "档案清单";            
            }
            else if (this.ParentForm.ParentForm.SystemConfig1.Language == DataStore.LanguageID.Czech)
            {
                this.labelTitleFileList.Text = "Seznam souborů";
            }
            else if (this.ParentForm.ParentForm.SystemConfig1.Language == DataStore.LanguageID.Russian)
            {
                this.labelTitleFileList.Text = "Список файлов";
            }
            else if (this.ParentForm.ParentForm.SystemConfig1.Language == DataStore.LanguageID.German)
            {
                this.labelTitleFileList.Text = "Dateiliste";
            }
            else if (this.ParentForm.ParentForm.SystemConfig1.Language == DataStore.LanguageID.Spanish)
            {
                this.labelTitleFileList.Text = "Lista de archivos";            
            }
            else
            {
                this.labelTitleFileList.Text = "파일 목록";               
            }
        }
        private void DefaultSetting()
        {
            this.FileIndex = 0;
        }

        private void FileCopy(FileInfo file, string fileName)
        {
            try
            {
                if (this.FileIndex == 0)
                {
                    file.CopyTo(fileName);
                    this.FileIndex = 0;
                }
                else
                {
                    file.CopyTo(fileName.Insert(fileName.Length - 4, "_" + this.FileIndex.ToString()));
                    this.FileIndex = 0;
                }
            }
            catch
            {
                this.FileIndex++;
                this.FileCopy(file, fileName);
            }
        }
        public void LoadFile(string fileName)
        {
            string fullFilePath = "";

            if (fileName.Contains("Exception") == false && fileName.Contains("Alarm") == false)
                return;

            fullFilePath = this.ParentForm.ParentForm.PathDataBackupFolder + fileName;
            this.smartFile1.FilePathName = fullFilePath;
            this.smartFile1.Open(this.ParentForm.ParentForm.BufferSmartUart);

            this.listBoxContents.Items.Clear();

            try
            {
                if (this.smartFile1.ReadStringAllBuffer() == true)
                {
                    long lineNum = this.smartFile1.GetCount();
                    for (int i = 0; i < lineNum; i++)
                    {
                        this.listBoxContents.Items.Add(this.smartFile1.ReadStringBuffer(i));
                    }

                    if (fileName.Contains("Alarm") == true)
                    {
                        this.listBoxContents.SelectedIndex = (int)lineNum - 1;
                    }
                }
            }
            catch
            {
                DialogFormMessage myMsg = new DialogFormMessage(16, this.ParentForm.ParentForm.SystemConfig1.Language);
                myMsg.ShowDialog();

                this.smartFile1.Close();
            }

            this.smartFile1.Close();
        }

        public void DisplayRefresh(SystemStatus status)
        {
            bool directoryCheck = false;
            int index = 0;

            this.ParentForm.ParentForm.CurrentSystemStatus.CurrentDisplay = DataStore.DisplayStore.EquipSystemLog;
            this.ParentForm.DisplayTitleRoot(this.ParentForm.ParentForm.CurrentSystemStatus);
            this.ParentForm.ParentForm.SetDisplayMode(DataStore.DisplayMode.Menu);

            this.listBoxContents.Items.Clear();

            DirectoryInfo dir = new DirectoryInfo(this.ParentForm.ParentForm.PathDataBackupFolder);

            directoryCheck = dir.Exists;
            // 폴더 체크
            if (directoryCheck == false)
                dir.Create();

            FileInfo[] files = dir.GetFiles();

            this.listBoxList.SelectedIndexChanged -= new EventHandler(this.listBoxList_SelectedIndexChanged);
            this.listBoxList.SelectedIndex = -1;
            this.listBoxList.Items.Clear();

            foreach (FileInfo file in files)
            {
                if (file.Name.Contains("Data") != true && file.Name.Contains("Stat") != true && file.Name.Contains(".jpg") != true)
                    this.listBoxList.Items.Add(file.Name);
            }

            this.labelFilesCount.Text = this.listBoxList.Items.Count.ToString();
            this.buttonFileView.Enabled = false;
            this.listBoxList.SelectedIndexChanged += new EventHandler(this.listBoxList_SelectedIndexChanged);
        }
        #endregion

        #region Event Handler
        private void listBoxList_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.listBoxList.SelectedItem.ToString().Contains("Exception") == true
                    || this.listBoxList.SelectedItem.ToString().Contains("Alarm") == true)
                    this.buttonFileView.Enabled = true;
                else
                    this.buttonFileView.Enabled = false;
            }
            catch
            {
                this.buttonFileView.Enabled = false;
            }
        }

        private void buttonFileView_Click(object sender, EventArgs e)
        {
            if (this.listBoxList.SelectedIndex == -1)
                return;

            this.LoadFile(this.listBoxList.SelectedItem.ToString());
        }
        private void buttonBackup_Click(object sender, EventArgs e)
        {
            if (this.listBoxList.Items.Count == 0)
            {
                DialogFormMessage msg = new DialogFormMessage(4, this.ParentForm.ParentForm.SystemConfig1.Language);
                msg.ShowDialog();
                return;
            }

            if (this.ParentForm.ParentForm.IsCommunicationLogOpen == true)
            {
                this.ParentForm.ParentForm.smartFileCommunicationLog.Close();
                this.ParentForm.ParentForm.IsCommunicationLogOpen = false;
            }
            if (this.ParentForm.ParentForm.IsErrorLogOpen == true)
            {
                this.ParentForm.ParentForm.smartFileCheckLog.Close();
                this.ParentForm.ParentForm.IsErrorLogOpen = false;
            }
            if (this.ParentForm.ParentForm.IsBarcodeLogOpen == true)
            {
                this.ParentForm.ParentForm.smartFileBarcodeLog.Close();
                this.ParentForm.ParentForm.IsBarcodeLogOpen = false;
            }
            this.ParentForm.ParentForm.smartFileStartStopLog.Close();

            int count = 0;
            bool directoryCheck = false;
            string filePath = "";
            DirectoryInfo dir = new DirectoryInfo(this.ParentForm.ParentForm.PathDataBackupFolder);
            directoryCheck = dir.Exists;
            // 폴더 체크
            if (directoryCheck == false)
                dir.Create();

            SmartSplash splash = new SmartSplash();
            splash.CenterPosition = true;
            splash.AnimationInterval = 200;
            splash.LoadingImagePathname = "SmartLoading4";
            splash.Start();

            try
            {
                DirectoryInfo dinfo = new DirectoryInfo("하드 디스크\\");
                dinfo.GetDirectories();
            }
            catch
            {
                splash.Finish();

                // USB메모리가 장착되지 않았습니다
                DialogFormMessage msg = new DialogFormMessage(5, this.ParentForm.ParentForm.SystemConfig1.Language);
                msg.ShowDialog();
                return;
            }

            this.listBoxList.SelectedIndexChanged -= new EventHandler(this.listBoxList_SelectedIndexChanged);
            try
            {
                if (this.listBoxList.SelectedIndex == -1)
                {
                    #region 전체 데이터 백업
                    try
                    {
                        filePath = "하드 디스크\\";

                        FileInfo[] files = dir.GetFiles();

                        foreach (FileInfo file in files)
                        {
                            if (file.Name.Contains("Data") != true && file.Name.Contains("Stat") != true && file.Name.Contains(".jpg") != true)
                            {
                                count++;
                                this.FileCopy(file, filePath + file.Name);
                                this.listBoxList.Items.Remove(file.Name);
                                file.Delete();
                            }
                        }
                        this.labelFilesCount.Text = this.listBoxList.Items.Count.ToString();

                        splash.Finish();

                        DialogFormMessage msg = new DialogFormMessage(count.ToString(), this.ParentForm.ParentForm.SystemConfig1.Language);
                        msg.ShowDialog();
                    }
                    catch
                    {
                        splash.Finish();

                        // 제조사에 문의하세요
                        DialogFormMessage msg = new DialogFormMessage(6, this.ParentForm.ParentForm.SystemConfig1.Language);
                        msg.ShowDialog();
                        return;
                    }
                    #endregion
                }
                else
                {
                    #region 선택 데이터 백업
                    try
                    {
                        filePath = "하드 디스크\\";

                        FileInfo[] files = dir.GetFiles();

                        foreach (FileInfo file in files)
                        {
                            if (file.Name.Contains(this.listBoxList.SelectedItem.ToString()) == true)
                            {
                                this.FileCopy(file, filePath + file.Name);
                                this.listBoxList.Items.Remove(file.Name);
                                file.Delete();
                                break;
                            }
                        }

                        this.labelFilesCount.Text = this.listBoxList.Items.Count.ToString();

                        splash.Finish();

                        DialogFormMessage msg = new DialogFormMessage("1", this.ParentForm.ParentForm.SystemConfig1.Language);
                        msg.ShowDialog();
                    }
                    catch
                    {
                        splash.Finish();

                        // 제조사에 문의하세요
                        DialogFormMessage msg = new DialogFormMessage(6, this.ParentForm.ParentForm.SystemConfig1.Language);
                        msg.ShowDialog();
                        return;
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                FormMain.Exception(ex);

                directoryCheck = dir.Exists;
                // 폴더 체크
                if (directoryCheck == false)
                    dir.Create();

                FileInfo[] files = dir.GetFiles();

                this.listBoxList.SelectedIndex = -1;
                this.listBoxList.Items.Clear();

                foreach (FileInfo file in files)
                {
                    if (file.Name.Contains("Data") != true && file.Name.Contains("Stat") != true && file.Name.Contains(".jpg") != true)
                        this.listBoxList.Items.Add(file.Name);
                }

                this.labelFilesCount.Text = this.listBoxList.Items.Count.ToString();
                this.buttonFileView.Enabled = false;
            }
            this.listBoxContents.Items.Clear();
            this.listBoxList.SelectedIndexChanged += new EventHandler(this.listBoxList_SelectedIndexChanged);

            if(this.ParentForm.ParentForm.SystemConfig3.IsStartStopLog == true)
                this.ParentForm.ParentForm.smartFileStartStopLog.Open();
        }

        private void buttonClear_Click(object sender, EventArgs e)
        {
            if (this.listBoxList.Items.Count == 0)
                return;

            this.ParentForm.ParentForm.smartFileCommunicationLog.Close();
            this.ParentForm.ParentForm.IsCommunicationLogOpen = false;
            this.ParentForm.ParentForm.smartFileStartStopLog.Close();
            this.ParentForm.ParentForm.smartFileCheckLog.Close();
            this.ParentForm.ParentForm.IsErrorLogOpen = false;

            bool directoryCheck = false;
            DirectoryInfo dir = new DirectoryInfo(this.ParentForm.ParentForm.PathDataBackupFolder);
            directoryCheck = dir.Exists;
            // 폴더 체크
            if (directoryCheck == false)
                dir.Create();

            FileInfo[] checkLogFiles = dir.GetFiles();

            this.listBoxList.SelectedIndexChanged -= new EventHandler(this.listBoxList_SelectedIndexChanged);
            try
            {
                DialogFormYesNo myDlg = new DialogFormYesNo(this.ParentForm.ParentForm.SystemConfig1.Language, 28);
                if (myDlg.ShowDialog() == DialogResult.Yes)
                {
                    SmartSplash splash = new SmartSplash();
                    splash.CenterPosition = true;
                    splash.AnimationInterval = 200;
                    splash.LoadingImagePathname = "SmartLoading4";
                    splash.Start();

                    if (this.listBoxList.SelectedIndex == -1)
                    {
                        #region ListBox 선택되지 않았을 때
                        try
                        {
                            FileInfo[] files = dir.GetFiles();

                            foreach (FileInfo file in files)
                            {
                                if (file.Name.Contains("Data") != true && file.Name.Contains("Stat") != true && file.Name.Contains(".jpg") != true)
                                {
                                    this.listBoxList.Items.Remove(file.Name);
                                    file.Delete();
                                }
                            }
                            this.labelFilesCount.Text = this.listBoxList.Items.Count.ToString();

                            splash.Finish();
                        }
                        catch
                        {
                            splash.Finish();

                            DialogFormMessage msg = new DialogFormMessage(6, this.ParentForm.ParentForm.SystemConfig1.Language);
                            msg.ShowDialog();
                            return;
                        }
                        #endregion
                    }
                    else
                    {
                        #region ListBox 선택되었을 때
                        try
                        {
                            if (this.listBoxList.SelectedIndex >= 0)
                            {
                                FileInfo[] files = dir.GetFiles();

                                foreach (FileInfo file in files)
                                {
                                    if (file.Name.Contains(this.listBoxList.SelectedItem.ToString()) == true)
                                    {
                                        this.listBoxList.Items.Remove(file.Name);
                                        file.Delete();
                                        break;
                                    }
                                }
                                this.labelFilesCount.Text = this.listBoxList.Items.Count.ToString();

                                splash.Finish();
                            }
                        }
                        catch
                        {
                            splash.Finish();

                            DialogFormMessage msg = new DialogFormMessage(6, this.ParentForm.ParentForm.SystemConfig1.Language);
                            msg.ShowDialog();
                            return;
                        }
                        #endregion
                    }
                }
            }
            catch (Exception ex)
            {
                FormMain.Exception(ex);

                directoryCheck = dir.Exists;
                // 폴더 체크
                if (directoryCheck == false)
                    dir.Create();

                FileInfo[] files = dir.GetFiles();

                this.listBoxList.SelectedIndex = -1;
                this.listBoxList.Items.Clear();

                foreach (FileInfo file in files)
                {
                    if (file.Name.Contains("Data") != true && file.Name.Contains("Stat") != true && file.Name.Contains(".jpg") != true)
                        this.listBoxList.Items.Add(file.Name);
                }

                this.labelFilesCount.Text = this.listBoxList.Items.Count.ToString();
                this.buttonFileView.Enabled = false;
            }
            this.listBoxContents.Items.Clear();
            this.listBoxList.SelectedIndexChanged += new EventHandler(this.listBoxList_SelectedIndexChanged);
        }
        #endregion
    }
}
