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 INT99DC_7C.Forms;
using INT99DC_7C.DialogForms;

namespace INT99DC_7C.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;
        private Collection<SmartLabel> CollectionMotorSettingLabel;
        #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 = "-";

                foreach (SmartLabel label in this.CollectionMotorSettingLabel)
                    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.labelWeightView);
            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.labelDamperDelayTime);
            this.CollectionSystemSettingLabel.Add(this.labelJudgmentCount);
            this.CollectionSystemSettingLabel.Add(this.labelSorterDelayTime);
            this.CollectionSystemSettingLabel.Add(this.labelSorterRunTime);

            this.CollectionCalibrationLabel = new Collection<SmartLabel>();
            this.CollectionCalibrationLabel.Add(this.labelZeroParameterTime);
            this.CollectionCalibrationLabel.Add(this.labelZeroParameterRange);
            this.CollectionCalibrationLabel.Add(this.labelZeroParameterVariate);

            this.CollectionMotorSettingLabel = new Collection<SmartLabel>();
            this.CollectionMotorSettingLabel.Add(this.labelMotorOrigin);
            this.CollectionMotorSettingLabel.Add(this.labelMotorSpeed0);
            this.CollectionMotorSettingLabel.Add(this.labelMotorSpeed1);
            this.CollectionMotorSettingLabel.Add(this.labelMotorPosition0);
            this.CollectionMotorSettingLabel.Add(this.labelMotorPosition1);
            this.CollectionMotorSettingLabel.Add(this.labelMotorPosition2);
        }

        public void ModbusOpen()
        {
            if (this.ParentForm.ParentForm.smartModbus.IsOpen == true)
                this.ParentForm.ParentForm.smartModbus.PortClose();

            try
            {
                this.ParentForm.ParentForm.smartModbus.PortOpen();
            }
            catch
            {
            }

        }
        public void ModbusClose()
        {
            this.ParentForm.ParentForm.smartModbus.PortClose();
        }
        private string ServoMotorRead1(int slaveAddress, int parameterAddress)
        {
            int value = 0;
            byte[] readData = new byte[2];

            this.ParentForm.ParentForm.smartModbus.SlaveAddress = slaveAddress;
            this.ParentForm.ParentForm.smartModbus.ReadHoldingRegister(parameterAddress, 1, ref readData);

            Array.Reverse(readData);
            value = BitConverter.ToInt16(readData, 0);

            return string.Format("{0}", value);
        }

        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)
        {
            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";                
        }
        private void UpdateCommunicationDisplay(SystemConfigurationItem item)
        {
            string value = "";

            value = item.Serial3BaudRate.ToString();
            if (this.labelCH3Baudrate.Text != value)
                this.labelCH3Baudrate.Text = value;

            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
                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;

            // 중량표시
            if (item.IsWeightViewForward == true)
                this.labelWeightView.Text = "Forward";
            else
                this.labelWeightView.Text = "Reverse";

            // 개별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.IsDischargeConveyorDirectionCW == true)
                this.labelDischargeConveyorDirection.Text = "CW";
            else
                this.labelDischargeConveyorDirection.Text = "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.DamperDelayTime.ToString();
            if (this.labelDamperDelayTime.Text != value)
                this.labelDamperDelayTime.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;
        }
        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;
        }
        public void UpdateMotorSettingDisplay()
        {
            this.ModbusOpen();
            Thread.Sleep(200);

            this.ParentForm.ParentForm.smartModbus.ReadTimeout = 500;

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

            this.Enabled = false;

            // ServoMotor 1
            this.labelMotorOrigin.Text = this.ServoMotorRead1(1, ServoMotorParameterAddress.CMD17);
            this.labelMotorSpeed0.Text = this.ServoMotorRead1(1, ServoMotorParameterAddress.Speed0);
            this.labelMotorSpeed1.Text = this.ServoMotorRead1(1, ServoMotorParameterAddress.Speed1);
            this.labelMotorPosition0.Text = this.ServoMotorRead1(1, ServoMotorParameterAddress.CMD0);
            this.labelMotorPosition1.Text = this.ServoMotorRead1(1, ServoMotorParameterAddress.CMD1);
            this.labelMotorPosition2.Text = this.ServoMotorRead1(1, ServoMotorParameterAddress.CMD2);

            splash.Finish();

            this.Enabled = true;

            this.ModbusClose();
        }

        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.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.ParameterRead3901, "");
        }
        private void buttonReadMotorSetting_Click(object sender, EventArgs e)
        {
            this.UpdateMotorSettingDisplay();
        }
        private void buttonAllRead_Click(object sender, EventArgs e)
        {
            // 환경설정
            this.ParentForm.ParentForm.TransferDataStream(CommunicationCommand.Read, CommunicationID.SubBoard1, CommunicationAddress.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.ParameterRead3901, "");
            Thread.Sleep(100);

            // 모터설정
            this.UpdateMotorSettingDisplay();
        }
        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}_Capture.jpg", this.ParentForm.ParentForm.PathDataBackupFolder, DateTime.Now);
            bitMap.Save(filePath, ImageFormat.Jpeg);
        }
        private void buttonFileBackup_Click(object sender, EventArgs e)
        {
            int index = 0;
            bool fileCheck = false, directoryCheck = false;
            string fullFilePath = "";
            StringBuilder sb = new StringBuilder();

            fullFilePath = string.Format("{0}{1:yyyyMMdd}_CheckList.csv", this.ParentForm.ParentForm.PathDataBackupFolder, DateTime.Now);
            this.ParentForm.ParentForm.smartFileIO.FilePathName = fullFilePath;

            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 < 40; i++)
                {
                    this.ParentForm.ParentForm.smartFileIO.WriteString("");
                }
            }
            else
            {
                this.ParentForm.ParentForm.smartFileIO.Open(this.ParentForm.ParentForm.BufferSmartUart);
            }

            this.ParentForm.ParentForm.smartFileIO.WriteString(string.Format("자동영점 시간,{0}", this.labelZeroParameterTime.Text), index);
            this.ParentForm.ParentForm.smartFileIO.WriteString(string.Format("자동영점 범위,{0}", this.labelZeroParameterRange.Text), index++);
            this.ParentForm.ParentForm.smartFileIO.WriteString(string.Format("자동영점 변량,{0}", this.labelZeroParameterVariate.Text), index++);

            this.ParentForm.ParentForm.smartFileIO.WriteString(string.Format("통신설정 CH3-속도,{0}", this.labelCH3Baudrate.Text), index++);
            this.ParentForm.ParentForm.smartFileIO.WriteString(string.Format("통신설정 CH3-모드,{0}", this.labelCH3Mode.Text), index++);

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

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

            this.ParentForm.ParentForm.smartFileIO.WriteString(string.Format("판정설정 필터,{0}", this.labelFilter.Text), index++);
            this.ParentForm.ParentForm.smartFileIO.WriteString(string.Format("판정설정 판정지연,{0}", this.labelJudgmentDelayTime.Text), index++);
            this.ParentForm.ParentForm.smartFileIO.WriteString(string.Format("판정설정 댐퍼동작지연,{0}", this.labelDamperDelayTime.Text), index++);
            this.ParentForm.ParentForm.smartFileIO.WriteString(string.Format("판정설정 판정개수,{0}", this.labelJudgmentCount.Text), index++);

            this.ParentForm.ParentForm.smartFileIO.WriteString(string.Format("선별기설정 지연시간,{0}", this.labelSorterDelayTime.Text), index++);
            this.ParentForm.ParentForm.smartFileIO.WriteString(string.Format("선별기설정 동작시간,{0}", this.labelSorterRunTime.Text), index++);

            this.ParentForm.ParentForm.smartFileIO.WriteString(string.Format("중량조정 분동중량,{0}", this.labelBalanceWeight.Text), index++);
            this.ParentForm.ParentForm.smartFileIO.WriteString(string.Format("중량조정 최대중량,{0}", this.labelMaxWeight.Text), index++);
            this.ParentForm.ParentForm.smartFileIO.WriteString(string.Format("중량조정 한눈의값,{0}", this.labelDigit.Text), index++);

            this.ParentForm.ParentForm.smartFileIO.WriteString(string.Format("모터설정 원점옵셋,{0}", this.labelMotorOrigin.Text), index++);
            this.ParentForm.ParentForm.smartFileIO.WriteString(string.Format("모터설정 원점속도,{0}", this.labelMotorSpeed0.Text), index++);
            this.ParentForm.ParentForm.smartFileIO.WriteString(string.Format("모터설정 속도1,{0}", this.labelMotorSpeed1.Text), index++);
            this.ParentForm.ParentForm.smartFileIO.WriteString(string.Format("모터설정 위치0,{0}", this.labelMotorPosition0.Text), index++);
            this.ParentForm.ParentForm.smartFileIO.WriteString(string.Format("모터설정 위치1,{0}", this.labelMotorPosition1.Text), index++);
            this.ParentForm.ParentForm.smartFileIO.WriteString(string.Format("모터설정 위치2,{0}", this.labelMotorPosition2.Text), index++);

            this.ParentForm.ParentForm.smartFileIO.Close();
        }
        #endregion
    }
}
