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

using SmartX;
using INT69DB_2A.Forms;

namespace INT69DB_2A.Controls
{
    public partial class ControlEquipmentTest : UserControl
    {
        #region Field
        private FormEquipmentTest m_ParentForm;

        private Collection<SmartLabel> CollectionConfigurationLabel;
        private Collection<SmartLabel> CollectionEquipmentSettingLabel;
        private Collection<SmartLabel> CollectionSystemSettingLabel;
        private Collection<SmartLabel> CollectionCalibrationLabel;
        #endregion

        #region Constructor
        public ControlEquipmentTest(FormEquipmentTest parent)
        {
            InitializeComponent();

            this.ParentForm = parent;

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

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

        #region Method
        private void InitializeControl()
        {
            if (this.CollectionConfigurationLabel != null && this.CollectionConfigurationLabel.Count != 0)
            {
                foreach (SmartLabel label in this.CollectionConfigurationLabel)
                    label.Text = "-";

                foreach (SmartLabel label in this.CollectionEquipmentSettingLabel)
                    label.Text = "-";

                foreach (SmartLabel label in this.CollectionSystemSettingLabel)
                    label.Text = "-";

                foreach (SmartLabel label in this.CollectionCalibrationLabel)
                    label.Text = "-";
            }
        }
        private void DefaultSetting()
        {
            this.CollectionConfigurationLabel = new Collection<SmartLabel>();
            this.CollectionConfigurationLabel.Add(this.labelZeroParameterTime);
            this.CollectionConfigurationLabel.Add(this.labelZeroParameterRange);
            this.CollectionConfigurationLabel.Add(this.labelZeroParameterVariate);
            this.CollectionConfigurationLabel.Add(this.labelCH3Baudrate);
            this.CollectionConfigurationLabel.Add(this.labelCH3Mode);
            this.CollectionConfigurationLabel.Add(this.labelDoubleEnter);
            this.CollectionConfigurationLabel.Add(this.labelChattering);
            this.CollectionConfigurationLabel.Add(this.labelBuzzerOnTime);
            this.CollectionConfigurationLabel.Add(this.labelRelayOnTime);
            this.CollectionConfigurationLabel.Add(this.labelDecimalPlaces);

            this.CollectionEquipmentSettingLabel = new Collection<SmartLabel>();
            this.CollectionEquipmentSettingLabel.Add(this.labelEquipmentMode);
            this.CollectionEquipmentSettingLabel.Add(this.labelEquipmentColumn);
            this.CollectionEquipmentSettingLabel.Add(this.labelIndividualNG);
            this.CollectionEquipmentSettingLabel.Add(this.labelInputSensorSelect);
            this.CollectionEquipmentSettingLabel.Add(this.labelDischargeConveyor);
            this.CollectionEquipmentSettingLabel.Add(this.labelDischargeConveyorDirection);
            this.CollectionEquipmentSettingLabel.Add(this.labelFeedingConveyor);
            this.CollectionEquipmentSettingLabel.Add(this.labelFeedingConveyorRun);
            this.CollectionEquipmentSettingLabel.Add(this.labelEquipmentID);
            this.CollectionEquipmentSettingLabel.Add(this.labelLanguage);

            this.CollectionSystemSettingLabel = new Collection<SmartLabel>();
            this.CollectionSystemSettingLabel.Add(this.labelFilter);
            this.CollectionSystemSettingLabel.Add(this.labelJudgmentDelayTime);
            this.CollectionSystemSettingLabel.Add(this.labelDoubleDelayTime);
            this.CollectionSystemSettingLabel.Add(this.labelJudgmentCount);
            this.CollectionSystemSettingLabel.Add(this.labelSorterDelayTime);
            this.CollectionSystemSettingLabel.Add(this.labelSorterRunTime);
            this.CollectionSystemSettingLabel.Add(this.labelRejectConveyorDelayTime);
            this.CollectionSystemSettingLabel.Add(this.labelRejectConveyorRunTime);
            this.CollectionSystemSettingLabel.Add(this.labelFeedingConveyorDelayTime);
            this.CollectionSystemSettingLabel.Add(this.labelFeedingConveyorRunTime);

            this.CollectionCalibrationLabel = new Collection<SmartLabel>();
            this.CollectionCalibrationLabel.Add(this.labelConstant1);
            this.CollectionCalibrationLabel.Add(this.labelConstant2);
            this.CollectionCalibrationLabel.Add(this.labelConstant3);
            this.CollectionCalibrationLabel.Add(this.labelConstant4);
            this.CollectionCalibrationLabel.Add(this.labelConstant5);
            this.CollectionCalibrationLabel.Add(this.labelConstant6);
            this.CollectionCalibrationLabel.Add(this.labelConstant7);
            this.CollectionCalibrationLabel.Add(this.labelConstant8);
            this.CollectionCalibrationLabel.Add(this.labelConstant9);
            this.CollectionCalibrationLabel.Add(this.labelConstant10);
            this.CollectionCalibrationLabel.Add(this.labelMaxWeight);
            this.CollectionCalibrationLabel.Add(this.labelBalanceWeight);
            this.CollectionCalibrationLabel.Add(this.labelDigit);
        }

        public void UpdateZeroParameterDisplay(DataStore.EquipmentStatus status, ZeroParameterItem item)
        {
            string sValue = "";

            sValue = item.Time.Trim();
            if (this.labelZeroParameterTime.Text != sValue)
                this.labelZeroParameterTime.Text = sValue;

            sValue = item.Range.Trim();
            if (this.labelZeroParameterRange.Text != sValue)
                this.labelZeroParameterRange.Text = sValue;

            sValue = item.Variate.Trim();
            if (sValue == "0")
                this.labelZeroParameterVariate.Text = "0.05";
            else if (sValue == "1")
                this.labelZeroParameterVariate.Text = "0.1";
            else if (sValue == "2")
                this.labelZeroParameterVariate.Text = "0.2";
            else if (sValue == "3")
                this.labelZeroParameterVariate.Text = "0.5";
            else if (sValue == "4")
                this.labelZeroParameterVariate.Text = "1.0";
            else if (sValue == "5")
                this.labelZeroParameterVariate.Text = "1.2";
            else
                this.labelZeroParameterVariate.Text = "0.05";
        }
        public void UpdateOptionParameterDisplay(DataStore.EquipmentStatus status, OptionParameterItem item, SystemConfigurationItem systemItem)
        {
            string value = "";

            value = item.Chattering.Trim();
            if (this.labelChattering.Text != value)
                this.labelChattering.Text = value;

            value = item.BuzzerOnTime.Trim();
            if (this.labelBuzzerOnTime.Text != value)
                this.labelBuzzerOnTime.Text = value;

            value = item.RelayOnTime.Trim();
            if (this.labelRelayOnTime.Text != value)
                this.labelRelayOnTime.Text = value;

            if (item.DoubleEnter == "1")
                this.labelDoubleEnter.Text = "ON";
            else
                this.labelDoubleEnter.Text = "OFF";

            if (systemItem.DecimalPlaces == 0)
                this.labelDecimalPlaces.Text = "0";
            else if (systemItem.DecimalPlaces == 1)
                this.labelDecimalPlaces.Text = "0.0";
            else if (systemItem.DecimalPlaces == 2)
                this.labelDecimalPlaces.Text = "0.00";
            else
                this.labelDecimalPlaces.Text = "0";

            this.UpdateCommunicationDisplay(systemItem);
        }
        private void UpdateCommunicationDisplay(SystemConfigurationItem item)
        {
            string value = "";

            if (item.Serial3BaudRate == 0)
                this.labelCH3Baudrate.Text = "9600";
            else if (item.Serial3BaudRate == 1)
                this.labelCH3Baudrate.Text = "19200";
            else if (item.Serial3BaudRate == 2)
                this.labelCH3Baudrate.Text = "38400";
            else if (item.Serial3BaudRate == 3)
                this.labelCH3Baudrate.Text = "115200";
            else
                this.labelCH3Baudrate.Text = "9600";

            if (item.Serial3Mode == 0)
                this.labelCH3Mode.Text = "None";
            else if (item.Serial3Mode == 1)
                this.labelCH3Mode.Text = "OPT1";
            else if (item.Serial3Mode == 2)
                this.labelCH3Mode.Text = "OPT2";
            else if (item.Serial3Mode == 3)
                this.labelCH3Mode.Text = "OPT3";
            else if (item.Serial3Mode == 4)
                this.labelCH3Mode.Text = "Printer";
            else if (item.Serial3Mode == 5)
                this.labelCH3Mode.Text = "OPT4";
            else
                this.labelCH3Mode.Text = "None";
        }
        public void UpdateEquipmentSettingDisplay(SystemConfigurationItem item)
        {
            int iValue = 0;
            string sValue = "";

            // 장비 타입
            iValue = item.EquipmentMode;
            if (iValue == 0)
                this.labelEquipmentMode.Text = "컨베어";
            else if (iValue == 1)
                this.labelEquipmentMode.Text = "스틱I";
            else if (iValue == 2)
                this.labelEquipmentMode.Text = "스틱II";
            else if (iValue == 3)
                this.labelEquipmentMode.Text = "스틱III";
            else if (iValue == 4)
                this.labelEquipmentMode.Text = "업다운";
            else if (iValue == 5)
                this.labelEquipmentMode.Text = "튜브";
            else
                this.labelEquipmentMode.Text = "컨베어";

            // 장비 열
            sValue = item.EquipmentColumns.ToString();
            if (this.labelEquipmentColumn.Text != sValue)
                this.labelEquipmentColumn.Text = sValue;

            // 개별NG
            if (item.IsEachNG == true)
                this.labelIndividualNG.Text = "ON";
            else
                this.labelIndividualNG.Text = "OFF";

            // 입력센서선택
            this.labelInputSensorSelect.Text = item.InputSensorSelect.ToString();

            // 선별컨베어
            if (item.IsDischargeConveyor == true)
                this.labelDischargeConveyor.Text = "ON";
            else
                this.labelDischargeConveyor.Text = "OFF";

            // 선별컨베어 회전방향
            if (item.DischargeConveyorDirectionCW == DataStore.DischargeConveyorDirection.CW)
                this.labelDischargeConveyorDirection.Text = "CW";
            else if (item.DischargeConveyorDirectionCW == DataStore.DischargeConveyorDirection.CCW)
                this.labelDischargeConveyorDirection.Text = "CCW";
            else
                this.labelDischargeConveyorDirection.Text = "CW/CCW";

            // 이송컨베어
            if (item.IsFeedingConveyor == true)
                this.labelFeedingConveyor.Text = "ON";
            else
                this.labelFeedingConveyor.Text = "OFF";


            // 이송컨베어 구동
            if (item.IsFeedingConveyorRunPass == true)
                this.labelFeedingConveyorRun.Text = "PASS";
            else
                this.labelFeedingConveyorRun.Text = "NG";

            // 장비 ID
            sValue = item.EquipmentID.ToString();
            if (this.labelEquipmentID.Text != sValue)
                this.labelEquipmentID.Text = sValue;

            // 언어
            sValue = item.Language.ToString();
            if (this.labelLanguage.Text != sValue)
                this.labelLanguage.Text = sValue;
        }
        private void UpdateSystemSettingDisplay(JudgmentSetItem item)
        {
            string value = "";

            // 필터
            value = item.Filter.ToString();
            if (this.labelFilter.Text != value)
                this.labelFilter.Text = value;

            // 판정지연
            value = item.JudgmentDelayTime.ToString();
            if (this.labelJudgmentDelayTime.Text != value)
                this.labelJudgmentDelayTime.Text = value;

            // 이중지연
            value = item.DoubleDelayTime.ToString();
            if (this.labelDoubleDelayTime.Text != value)
                this.labelDoubleDelayTime.Text = value;

            // 판정개수
            value = item.JudgmentCount.ToString();
            if (this.labelJudgmentCount.Text != value)
                this.labelJudgmentCount.Text = value;

            // 선별기 지연시간
            value = item.Sorter1DelayTime.ToString();
            if (this.labelSorterDelayTime.Text != value)
                this.labelSorterDelayTime.Text = value;

            // 선별기 동작시간
            value = item.Sorter1RunTime.ToString();
            if (this.labelSorterRunTime.Text != value)
                this.labelSorterRunTime.Text = value;

            // 선별컨베어 지연시간
            value = item.RejectConveyorDelayTime.ToString();
            if (this.labelRejectConveyorDelayTime.Text != value)
                this.labelRejectConveyorDelayTime.Text = value;

            // 선별컨베어 동작시간
            value = item.RejectConveyorRunTime.ToString();
            if (this.labelRejectConveyorRunTime.Text != value)
                this.labelRejectConveyorRunTime.Text = value;

            // 이송컨베어 지연시간
            value = item.FeedingConveyorDelayTime.ToString();
            if (this.labelFeedingConveyorDelayTime.Text != value)
                this.labelFeedingConveyorDelayTime.Text = value;

            // 이송컨베어 동작시간
            value = item.FeedingConveyorRunTime.ToString();
            if (this.labelFeedingConveyorRunTime.Text != value)
                this.labelFeedingConveyorRunTime.Text = value;
        }
        public void UpdateCalibrationDisplay(CalibrationItem item)
        {
            string value = "";

            // 분동중량
            value = item.BalanceWeight;
            if (this.labelBalanceWeight.Text != value)
                this.labelBalanceWeight.Text = value;

            // 최대중량
            value = item.MaxWeight;
            if (this.labelMaxWeight.Text != value)
                this.labelMaxWeight.Text = value;

            // 한눈의값
            value = item.Digit;
            if (this.labelDigit.Text != value)
                this.labelDigit.Text = value;

            // Constant 1
            value = Helper.StringToDecimalPlaces(item.Constant1.Trim(), 6);
            if (this.labelConstant1.Text != value)
                this.labelConstant1.Text = value;

            // Constant 2
            value = Helper.StringToDecimalPlaces(item.Constant2.Trim(), 6);
            if (this.labelConstant2.Text != value)
                this.labelConstant2.Text = value;

            // Constant 3
            value = Helper.StringToDecimalPlaces(item.Constant3.Trim(), 6);
            if (this.labelConstant3.Text != value)
                this.labelConstant3.Text = value;

            // Constant 4
            value = Helper.StringToDecimalPlaces(item.Constant4.Trim(), 6);
            if (this.labelConstant4.Text != value)
                this.labelConstant4.Text = value;

            // Constant 5
            value = Helper.StringToDecimalPlaces(item.Constant5.Trim(), 6);
            if (this.labelConstant5.Text != value)
                this.labelConstant5.Text = value;

            // Constant 6
            value = Helper.StringToDecimalPlaces(item.Constant6.Trim(), 6);
            if (this.labelConstant6.Text != value)
                this.labelConstant6.Text = value;

            // Constant 7
            value = Helper.StringToDecimalPlaces(item.Constant7.Trim(), 6);
            if (this.labelConstant7.Text != value)
                this.labelConstant7.Text = value;

            // Constant 8
            value = Helper.StringToDecimalPlaces(item.Constant8.Trim(), 6);
            if (this.labelConstant8.Text != value)
                this.labelConstant8.Text = value;

            // Constant 9
            value = Helper.StringToDecimalPlaces(item.Constant9.Trim(), 6);
            if (this.labelConstant9.Text != value)
                this.labelConstant9.Text = value;

            // Constant 10
            value = Helper.StringToDecimalPlaces(item.Constant10.Trim(), 6);
            if (this.labelConstant10.Text != value)
                this.labelConstant10.Text = value;
        }
       
        public void DisplayRefresh()
        {
            this.InitializeControl();
        }
        #endregion

        #region Event Handler
        private void buttonReadConfiguration_Click(object sender, EventArgs e)
        {
            this.ParentForm.ParentForm.TransferDataStream(CommunicationCommand.Read, CommunicationID.SubBoard1, CommunicationAddress._4901_ParameterRead4901, "");
        }
        private void buttonReadEquipmentSetting_Click(object sender, EventArgs e)
        {
            this.UpdateEquipmentSettingDisplay(this.ParentForm.ParentForm.SystemConfig);
        }
        private void buttonReadSystemSetting_Click(object sender, EventArgs e)
        {
            this.UpdateSystemSettingDisplay(this.ParentForm.ParentForm.CurrentJudgmentSetItem);
        }
        private void buttonReadCalibration_Click(object sender, EventArgs e)
        {
            this.ParentForm.ParentForm.TransferDataStream(CommunicationCommand.Read, CommunicationID.SubBoardAll, CommunicationAddress._3901_ParameterRead3901, "");
        }
        private void buttonAllRead_Click(object sender, EventArgs e)
        {
            // 환경설정
            this.ParentForm.ParentForm.TransferDataStream(CommunicationCommand.Read, CommunicationID.SubBoard1, CommunicationAddress._4901_ParameterRead4901, "");
            Thread.Sleep(100);

            // 장비설정
            this.UpdateEquipmentSettingDisplay(this.ParentForm.ParentForm.SystemConfig);
            Thread.Sleep(100);

            // 시스템설정
            this.UpdateSystemSettingDisplay(this.ParentForm.ParentForm.CurrentJudgmentSetItem);
            Thread.Sleep(100);

            // 중량조정
            this.ParentForm.ParentForm.TransferDataStream(CommunicationCommand.Read, CommunicationID.SubBoardAll, CommunicationAddress._3901_ParameterRead3901, "");
        }
        private void buttonCapture_Click(object sender, EventArgs e)
        {
            string filePath = "";
            Bitmap bitMap = new Bitmap(800, 480);

            bitMap = IntechGraphics.CopyFromScreen();
            filePath = string.Format("{0}{1:yyyyMMdd_HHmm}_{2}_CheckListCapture.jpg",
                this.ParentForm.ParentForm.PathDataBackupFolder, DateTime.Now, this.ParentForm.ParentForm.SystemConfig.SerialNumber);
            bitMap.Save(filePath, ImageFormat.Jpeg);
        }
        private void buttonFileBackup_Click(object sender, EventArgs e)
        {
            bool fileCheck = false;
            string fullFilePath = "";
            StreamWriter sw;

            fullFilePath = string.Format("{0}{1:yyyyMMdd_HHmm}_{2}_CheckList.csv",
                this.ParentForm.ParentForm.PathDataBackupFolder, DateTime.Now, this.ParentForm.ParentForm.SystemConfig.SerialNumber);
            this.ParentForm.ParentForm.smartFileIO.FilePathName = fullFilePath;
            sw = new StreamWriter(fullFilePath, true, Encoding.Default);

            FileInfo fileInfo = new FileInfo(fullFilePath);
            fileCheck = fileInfo.Exists;

            if (fileCheck == true)
            {
                this.ParentForm.ParentForm.smartFileIO.Open(this.ParentForm.ParentForm.BufferSmartUart);

                for (int i = 0; i < 45; i++)
                {
                    this.ParentForm.ParentForm.smartFileIO.WriteString("");
                }
                this.ParentForm.ParentForm.smartFileIO.Close();
            }

            sw.WriteLine(string.Format("자동영점 시간,{0}", this.labelZeroParameterTime.Text));
            sw.WriteLine(string.Format("자동영점 범위,{0}", this.labelZeroParameterRange.Text));
            sw.WriteLine(string.Format("자동영점 변량,'{0}", this.labelZeroParameterVariate.Text));

            sw.WriteLine(string.Format("통신설정 CH3-속도,{0}", this.labelCH3Baudrate.Text));
            sw.WriteLine(string.Format("통신설정 CH3-모드,{0}", this.labelCH3Mode.Text));

            sw.WriteLine(string.Format("기타옵션 이중진입,{0}", this.labelDoubleEnter.Text));
            sw.WriteLine(string.Format("기타옵션 채터링감지,{0}", this.labelChattering.Text));
            sw.WriteLine(string.Format("기타옵션 부저ON시간,{0}", this.labelBuzzerOnTime.Text));
            sw.WriteLine(string.Format("기타옵션 릴레이ON시간,{0}", this.labelRelayOnTime.Text));
            sw.WriteLine(string.Format("기타옵션 소수점,'{0}", this.labelDecimalPlaces.Text));

            sw.WriteLine(string.Format("장비설정 장비타입,{0}", this.labelEquipmentMode.Text));
            sw.WriteLine(string.Format("장비설정 장비열,{0}", this.labelEquipmentColumn.Text));
            sw.WriteLine(string.Format("장비설정 개별NG,{0}", this.labelIndividualNG.Text));
            sw.WriteLine(string.Format("장비설정 입력센서선택,{0}", this.labelInputSensorSelect.Text));
            sw.WriteLine(string.Format("장비설정 선별컨베어,{0}", this.labelDischargeConveyor.Text));
            sw.WriteLine(string.Format("장비설정 선별컨베어회전방향,{0}", this.labelDischargeConveyorDirection.Text));
            sw.WriteLine(string.Format("장비설정 이송컨베어,{0}", this.labelFeedingConveyor.Text));
            sw.WriteLine(string.Format("장비설정 이송컨베어구동,{0}", this.labelFeedingConveyorRun.Text));
            sw.WriteLine(string.Format("장비설정 장비ID,{0}", this.labelEquipmentID.Text));
            sw.WriteLine(string.Format("장비설정 언어,{0}", this.labelLanguage.Text));

            sw.WriteLine(string.Format("판정설정 필터,{0}", this.labelFilter.Text));
            sw.WriteLine(string.Format("판정설정 판정지연,{0}", this.labelJudgmentDelayTime.Text));
            sw.WriteLine(string.Format("판정설정 이중지연,{0}", this.labelDoubleDelayTime.Text));
            sw.WriteLine(string.Format("판정설정 판정개수,{0}", this.labelJudgmentCount.Text));

            sw.WriteLine(string.Format("선별기설정 지연시간,{0}", this.labelSorterDelayTime.Text));
            sw.WriteLine(string.Format("선별기설정 동작시간,{0}", this.labelSorterRunTime.Text));

            sw.WriteLine(string.Format("선별컨베어 지연시간,{0}", this.labelRejectConveyorDelayTime.Text));
            sw.WriteLine(string.Format("선별컨베어 동작시간,{0}", this.labelRejectConveyorRunTime.Text));

            sw.WriteLine(string.Format("이송컨베어 지연시간,{0}", this.labelFeedingConveyorDelayTime.Text));
            sw.WriteLine(string.Format("이송컨베어 동작시간,{0}", this.labelFeedingConveyorRunTime.Text));

            sw.WriteLine(string.Format("중량조정 분동중량,{0}", this.labelBalanceWeight.Text));
            sw.WriteLine(string.Format("중량조정 최대중량,{0}", this.labelMaxWeight.Text));
            sw.WriteLine(string.Format("중량조정 한눈의값,{0}", this.labelDigit.Text));
            sw.WriteLine(string.Format("Constant 1,'{0}", this.labelConstant1.Text));
            sw.WriteLine(string.Format("Constant 2,'{0}", this.labelConstant2.Text));
            sw.WriteLine(string.Format("Constant 3,'{0}", this.labelConstant3.Text));
            sw.WriteLine(string.Format("Constant 4,'{0}", this.labelConstant4.Text));
            sw.WriteLine(string.Format("Constant 5,'{0}", this.labelConstant5.Text));
            sw.WriteLine(string.Format("Constant 6,'{0}", this.labelConstant6.Text));
            sw.WriteLine(string.Format("Constant 7,'{0}", this.labelConstant7.Text));
            sw.WriteLine(string.Format("Constant 8,'{0}", this.labelConstant8.Text));
            sw.WriteLine(string.Format("Constant 9,'{0}", this.labelConstant9.Text));
            sw.WriteLine(string.Format("Constant 10,'{0}", this.labelConstant10.Text));

            sw.Close();
        }
        #endregion
    }
}
