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

using SmartX;

using INT51DB_ImageDll;
using INT51DB.Forms;
using INT51DB.DialogForms;

namespace INT51DB.Controls
{
    public partial class ControlCenterSystemServoMotor : UserControl
    {
        #region Field
        private FormMenu m_ParentForm;
        #endregion

        #region Constructor
        public ControlCenterSystemServoMotor(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()
        {
            Class1 images = new Class1();

            if (this.ParentForm.ParentForm.SystemConfig.Language == DataStore.LanguageID.English)
            {
            }
            else if (this.ParentForm.ParentForm.SystemConfig.Language == DataStore.LanguageID.Chinese)
            {
            }
            else if (this.ParentForm.ParentForm.SystemConfig.Language == DataStore.LanguageID.Czech)
            {
            }
            else
            {
            }
        }
        private void DefaultSetting()
        {
        }

        private void ModbusStatusDisplay(bool isOpen)
        {
            if (isOpen == true)
            {
                this.labelModusStatus.Text = "OPEN";
                this.labelModusStatus.BackColor = Color.DarkGreen;
                this.labelModusStatus.ForeColor = Color.White;
            }
            else
            {
                this.labelModusStatus.Text = "CLOSE";
                this.labelModusStatus.BackColor = Color.Crimson;
                this.labelModusStatus.ForeColor = Color.White;
            }
        }
        public void ModbusOpen()
        {
            if (this.ParentForm.ParentForm.smartModbus.IsOpen == true)
                this.ParentForm.ParentForm.smartModbus.PortClose();

            try
            {
                this.ParentForm.ParentForm.smartModbus.PortOpen();
                Thread.Sleep(200);
                this.ModbusStatusDisplay(this.ParentForm.ParentForm.smartModbus.IsOpen);
            }
            catch
            {
            }
            
        }
        public void ModbusClose()
        {
            this.ParentForm.ParentForm.smartModbus.PortClose();
            this.ModbusStatusDisplay(this.ParentForm.ParentForm.smartModbus.IsOpen);
        }

        private void ServoMotorWrite(int slaveAddress, int parameterAddress, float value)
        {
            byte[] writeData = new byte[4];
            byte[] readData = new byte[8];

            writeData = BitConverter.GetBytes(value);
            Array.Reverse(writeData);

            this.ParentForm.ParentForm.smartModbus.SlaveAddress = slaveAddress;
            if (this.ParentForm.ParentForm.smartModbus.DirectParameter(0x06, parameterAddress, 1, writeData, ref readData) == SmartX.SmartModbus.EXCEPTIONCODE.SUCCESS)
            {
                MessageBox.Show("쓰기완료");
            }
        }
        private string ServoMotorRead(int slaveAddress, int parameterAddress)
        {
            float value;
            byte[] readData = new byte[4];

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

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

            return string.Format("{0:0}", value);
        }
        private string ServoMotorAlarmRead(int slaveAddress, int functionCode, int startAddress, byte[] writeData)
        {
            string currentAlarm = "";
            byte[] readData = new byte[4];

            this.ParentForm.ParentForm.smartModbus.SlaveAddress = slaveAddress;
            if (this.ParentForm.ParentForm.smartModbus.DirectParameter(functionCode, startAddress, 1, writeData, ref readData) == SmartModbus.EXCEPTIONCODE.SUCCESS)
            {
                MessageBox.Show("알람 읽기 완료!!");
            }

            currentAlarm = this.ServoMotorCurrentAlarmRead(readData[3]);

            return currentAlarm;
        }
        private string ServoMotorCurrentAlarmRead(byte readData)
        {
            string alarm = "";

            if (readData == ServoMotorAlarmList.AL00_NORMAL_ESTOP)
                alarm = "AL00_NORMAL_ESTOP";
            else if (readData == ServoMotorAlarmList.AL01_OVER_CURNT)
                alarm = "AL01_OVER_CURNT";
            else if (readData == ServoMotorAlarmList.AL02_OVER_VOLT)
                alarm = "AL02_OVER_VOLT";
            else if (readData == ServoMotorAlarmList.AL03_OVER_LOAD)
                alarm = "AL03_OVER_LOAD";
            else if (readData == ServoMotorAlarmList.AL04_POWER_FAIL)
                alarm = "AL04_POWER_FAIL";
            else if (readData == ServoMotorAlarmList.AL05_LINE_FAIL)
                alarm = "AL05_LINE_FAIL";
            else if (readData == ServoMotorAlarmList.AL06_OVER_SPEED)
                alarm = "AL06_OVER_SPEED";
            else if (readData == ServoMotorAlarmList.AL07_FOLLOW_ERR)
                alarm = "AL07_FOLLOW_ERR";
            else if (readData == ServoMotorAlarmList.AL08_OUTPUT_NC)
                alarm = "AL08_OUTPUT_NC";
            else if (readData == ServoMotorAlarmList.AL09_PPR_ERROR)
                alarm = "AL09_PPR_ERROR";
            else if (readData == ServoMotorAlarmList.AL10_ABS_DATA)
                alarm = "AL10_ABS_DATA";
            else if (readData == ServoMotorAlarmList.AL11_ABS_BATT)
                alarm = "AL11_ABS_BATT";
            else if (readData == ServoMotorAlarmList.AL12_ABS_MDER)
                alarm = "AL12_ABS_MDER";
            else if (readData == ServoMotorAlarmList.AL13_POWER_LINE)
                alarm = "AL13_POWER_LINE";
            else if (readData == ServoMotorAlarmList.AL14_ABS_LOW_BATT)
                alarm = "AL14_ABS_LOW_BATT";
            else if (readData == ServoMotorAlarmList.AL15_ERASE_FAIL)
                alarm = "AL15_ERASE_FAIL";
            else if (readData == ServoMotorAlarmList.AL16_WRITE_FAIL)
                alarm = "AL16_WRITE_FAIL";
            else if (readData == ServoMotorAlarmList.AL17_PARA_INIT)
                alarm = "AL17_PARA_INIT";
            else
                alarm = "Current Alarm";

            return alarm;
        }

        public void DisplayRefresh(DataStore.UserGroup group)
        {
            this.ParentForm.ParentForm.CurrentSystemStatus.CurrentDisplay = DataStore.DisplayStore.SystemServoMotor;
            this.ParentForm.ParentForm.SetDisplayMode(DataStore.DisplayMode.IOTest);
            this.ParentForm.DisplayTitleRoot(this.ParentForm.ParentForm.CurrentSystemStatus);

            this.ParentForm.ParentForm.TransferData(CommunicationCommand.ModeIOTest, CommunicationID.MainBoard);

            this.ModbusClose();

            this.labelMotorAlarmRead.Text = "Current Alarm";
        }
        #endregion

        #region Event Handler
        // Open
        private void buttonOpen_Click(object sender, EventArgs e)
        {
            this.ModbusOpen();
        }

        // Close
        private void buttonClose_Click(object sender, EventArgs e)
        {
            this.ModbusClose();
        }

        // Parameter Read
        private void buttonParameterRead_Click(object sender, EventArgs e)
        {
            if (this.ParentForm.ParentForm.smartModbus.IsOpen == false)
            {
                // 통신 연결상태를 확인하세요
                DialogFormMessage myMsg = new DialogFormMessage(23, this.ParentForm.ParentForm.SystemConfig.Language);
                myMsg.ShowDialog();
                return;
            }

            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.labelOrigin.Text = this.ServoMotorRead(1, ServoMotorParameterAddress.OriginOffset);
            this.labelORGSpeed.Text = this.ServoMotorRead(1, ServoMotorParameterAddress.ORGSpeed0);
            this.labelSpeed0.Text = this.ServoMotorRead(1, ServoMotorParameterAddress.GropSpeed0);
            this.labelSpeed1.Text = this.ServoMotorRead(1, ServoMotorParameterAddress.GropSpeed1);
            this.labelPosition0.Text = this.ServoMotorRead(1, ServoMotorParameterAddress.PositionCMD0);
            this.labelPosition1.Text = this.ServoMotorRead(1, ServoMotorParameterAddress.PositionCMD1);
            this.labelPosition9.Text = this.ServoMotorRead(1, ServoMotorParameterAddress.PositionCMD9);

            splash.Finish();

            this.Enabled = true;
        }

        // Parameter Setting
        private void labelMotorParameterSetup_Click(object sender, EventArgs e)
        {
            float fValue = float.NaN;

            SmartLabel label = sender as SmartLabel;

            if (label == null)
                return;

            if (this.ParentForm.ParentForm.smartModbus.IsOpen == false)
            {
                // 통신 연결상태를 확인하세요
                DialogFormMessage myMsg = new DialogFormMessage(23, this.ParentForm.ParentForm.SystemConfig.Language);
                myMsg.ShowDialog();
                return;
            }

            if (label == this.labelOrigin)
            {
                #region UpDown Motor - Origin
                DialogFormNumKeyPad myKeyPad = new DialogFormNumKeyPad(this.labelOrigin.Text, 4, 0, true, this.ParentForm.ParentForm.SystemConfig.Language);

                if (myKeyPad.ShowDialog() == DialogResult.OK)
                {
                    if (myKeyPad.doubleValue < -9999 || myKeyPad.doubleValue > 9999)
                    {
                        // 입력범위를 확인하세요
                        DialogFormMessage myMsg = new DialogFormMessage(1, this.ParentForm.ParentForm.SystemConfig.Language);
                        myMsg.ShowDialog();
                    }
                    else
                    {
                        this.labelOrigin.Text = myKeyPad.StringValue;

                        fValue = Convert.ToSingle(this.labelOrigin.Text);

                        this.ServoMotorWrite(2, ServoMotorParameterAddress.OriginOffset, fValue);
                    }
                }
                #endregion
            }
            else if (label == this.labelORGSpeed)
            {
                #region UpDown Motor ORG Speed
                DialogFormNumKeyPad myKeyPad = new DialogFormNumKeyPad(this.labelORGSpeed.Text, 4, 0, false, this.ParentForm.ParentForm.SystemConfig.Language);

                if (myKeyPad.ShowDialog() == DialogResult.OK)
                {
                    if (myKeyPad.doubleValue < 0 || myKeyPad.doubleValue > 9999)
                    {
                        // 입력범위를 확인하세요
                        DialogFormMessage myMsg = new DialogFormMessage(1, this.ParentForm.ParentForm.SystemConfig.Language);
                        myMsg.ShowDialog();
                    }
                    else
                    {
                        this.labelORGSpeed.Text = myKeyPad.StringValue;

                        fValue = Convert.ToSingle(this.labelORGSpeed.Text);

                        this.ServoMotorWrite(2, ServoMotorParameterAddress.ORGSpeed0, fValue);
                    }
                }
                #endregion
            }
            else if (label == this.labelSpeed0)
            {
                #region UpDown Motor Speed 0
                DialogFormNumKeyPad myKeyPad = new DialogFormNumKeyPad(this.labelSpeed0.Text, 4, 0, false, this.ParentForm.ParentForm.SystemConfig.Language);

                if (myKeyPad.ShowDialog() == DialogResult.OK)
                {
                    if (myKeyPad.doubleValue < 0 || myKeyPad.doubleValue > 9999)
                    {
                        // 입력범위를 확인하세요
                        DialogFormMessage myMsg = new DialogFormMessage(1, this.ParentForm.ParentForm.SystemConfig.Language);
                        myMsg.ShowDialog();
                    }
                    else
                    {
                        this.labelSpeed0.Text = myKeyPad.StringValue;

                        fValue = Convert.ToSingle(this.labelSpeed0.Text);

                        this.ServoMotorWrite(2, ServoMotorParameterAddress.GropSpeed0, fValue);
                    }
                }
                #endregion
            }
            else if (label == this.labelSpeed1)
            {
                #region UpDown Motor Speed 1
                DialogFormNumKeyPad myKeyPad = new DialogFormNumKeyPad(this.labelSpeed1.Text, 4, 0, false, this.ParentForm.ParentForm.SystemConfig.Language);

                if (myKeyPad.ShowDialog() == DialogResult.OK)
                {
                    if (myKeyPad.doubleValue < 0 || myKeyPad.doubleValue > 9999)
                    {
                        // 입력범위를 확인하세요
                        DialogFormMessage myMsg = new DialogFormMessage(1, this.ParentForm.ParentForm.SystemConfig.Language);
                        myMsg.ShowDialog();
                    }
                    else
                    {
                        this.labelSpeed1.Text = myKeyPad.StringValue;

                        fValue = Convert.ToSingle(this.labelSpeed1.Text);

                        this.ServoMotorWrite(2, ServoMotorParameterAddress.GropSpeed1, fValue);
                    }
                }
                #endregion
            }
            else if (label == this.labelPosition0)
            {
                #region UpDown Motor Position 0
                DialogFormNumKeyPad myKeyPad = new DialogFormNumKeyPad(this.labelPosition0.Text, 4, 0, true, this.ParentForm.ParentForm.SystemConfig.Language);

                if (myKeyPad.ShowDialog() == DialogResult.OK)
                {
                    if (myKeyPad.doubleValue < -9999 || myKeyPad.doubleValue > 9999)
                    {
                        // 입력범위를 확인하세요
                        DialogFormMessage myMsg = new DialogFormMessage(1, this.ParentForm.ParentForm.SystemConfig.Language);
                        myMsg.ShowDialog();
                    }
                    else
                    {
                        this.labelPosition0.Text = myKeyPad.StringValue;

                        fValue = Convert.ToSingle(this.labelPosition0.Text);

                        this.ServoMotorWrite(2, ServoMotorParameterAddress.PositionCMD0, fValue);
                        this.ServoMotorWrite(2, ServoMotorParameterAddress.PositionCMD8, fValue);
                    }
                }
                #endregion
            }
            else if (label == this.labelPosition1)
            {
                #region UpDown Motor Position 1
                DialogFormNumKeyPad myKeyPad = new DialogFormNumKeyPad(this.labelPosition1.Text, 4, 0, true, this.ParentForm.ParentForm.SystemConfig.Language);

                if (myKeyPad.ShowDialog() == DialogResult.OK)
                {
                    if (myKeyPad.doubleValue < -9999 || myKeyPad.doubleValue > 9999)
                    {
                        // 입력범위를 확인하세요
                        DialogFormMessage myMsg = new DialogFormMessage(1, this.ParentForm.ParentForm.SystemConfig.Language);
                        myMsg.ShowDialog();
                    }
                    else
                    {
                        this.labelPosition1.Text = myKeyPad.StringValue;

                        fValue = Convert.ToSingle(this.labelPosition1.Text);

                        this.ServoMotorWrite(2, ServoMotorParameterAddress.PositionCMD1, fValue);
                    }
                }
                #endregion
            }
            else if (label == this.labelPosition9)
            {
                #region UpDown Motor Position 9
                DialogFormNumKeyPad myKeyPad = new DialogFormNumKeyPad(this.labelPosition9.Text, 4, 0, true, this.ParentForm.ParentForm.SystemConfig.Language);

                if (myKeyPad.ShowDialog() == DialogResult.OK)
                {
                    if (myKeyPad.doubleValue < -9999 || myKeyPad.doubleValue > 9999)
                    {
                        // 입력범위를 확인하세요
                        DialogFormMessage myMsg = new DialogFormMessage(1, this.ParentForm.ParentForm.SystemConfig.Language);
                        myMsg.ShowDialog();
                    }
                    else
                    {
                        this.labelPosition9.Text = myKeyPad.StringValue;

                        fValue = Convert.ToSingle(this.labelPosition9.Text);

                        this.ServoMotorWrite(2, ServoMotorParameterAddress.PositionCMD9, fValue);
                    }
                }
                #endregion
            }
        }

        // Alarm Reset
        private void buttonAlarmReset_Click(object sender, EventArgs e)
        {
            this.ParentForm.ParentForm.TransferData(CommunicationCommand.MotorAlarmReset, CommunicationID.MainBoard);
            //메인화면 서보알람 아이콘 표시
            //this.pMainForm.ChildFormMainDisplay.DisplayMotorAlarmView(false);
        }

        // Alarm Read
        private void buttonAlarmRead_Click(object sender, EventArgs e)
        {
            byte[] writeData = { 0x00, 0x00, 0x00, 0x01 };
            string currentAlarm = "";

            if (this.ParentForm.ParentForm.smartModbus.IsOpen == false)
            {
                // 통신 연결상태를 확인하세요
                DialogFormMessage myMsg = new DialogFormMessage(23, this.ParentForm.ParentForm.SystemConfig.Language);
                myMsg.ShowDialog();
                return;
            }

            this.ParentForm.ParentForm.smartModbus.ReadTimeout = 1000;

            currentAlarm = this.ServoMotorAlarmRead(1, 80, 2100, writeData);

            this.labelMotorAlarmRead.Text = currentAlarm;
        }

        // Alarm Code View
        private void labelMotorAlarmRead_Click(object sender, EventArgs e)
        {
            DialogFormMotorAlarmCode alarmCode = new DialogFormMotorAlarmCode();
            alarmCode.ShowDialog();
        }

        private void buttonConveyorUp2_Click(object sender, EventArgs e)
        {
            DialogFormYesNo msg = new DialogFormYesNo(this.ParentForm.ParentForm.SystemConfig.Language, 15);
            if (msg.ShowDialog() == DialogResult.Yes)
            {
                this.ParentForm.ParentForm.TransferData(CommunicationCommand.MotorUp2, CommunicationID.MainBoard);
                this.ParentForm.CurrentControlEnable(false);
            }
        }
        private void buttonConveyorUp_Click(object sender, EventArgs e)
        {
            DialogFormYesNo msg = new DialogFormYesNo(this.ParentForm.ParentForm.SystemConfig.Language, 14);
            if (msg.ShowDialog() == DialogResult.Yes)
            {
                this.ParentForm.ParentForm.TransferData(CommunicationCommand.MotorUp, CommunicationID.MainBoard);
                this.ParentForm.CurrentControlEnable(true);
            }
        }
        private void buttonConveyorDown_Click(object sender, EventArgs e)
        {
            DialogFormYesNo msg = new DialogFormYesNo(this.ParentForm.ParentForm.SystemConfig.Language, 13);
            if (msg.ShowDialog() == DialogResult.Yes)
            {
                this.ParentForm.ParentForm.TransferData(CommunicationCommand.MotorDown, CommunicationID.MainBoard);
                this.ParentForm.CurrentControlEnable(true);
            }
        }
        private void buttonConveyorForward_Click(object sender, EventArgs e)
        {
            this.ParentForm.ParentForm.TransferData(CommunicationCommand.MotorForward, CommunicationID.MainBoard);
        }
        private void buttonConveyorReverse_Click(object sender, EventArgs e)
        {
            this.ParentForm.ParentForm.TransferData(CommunicationCommand.MotorReverse, CommunicationID.MainBoard);
        }
        private void buttonOrigin_Click(object sender, EventArgs e)
        {
            this.ParentForm.ParentForm.TransferData(CommunicationCommand.MotorOrigin, CommunicationID.SubBoard1);
        }
        private void buttonStop_Click(object sender, EventArgs e)
        {
            this.ParentForm.ParentForm.TransferData(CommunicationCommand.Stop, CommunicationID.MainBoard);
        }
        private void buttonStart_Click(object sender, EventArgs e)
        {
            this.ParentForm.ParentForm.TransferData(CommunicationCommand.Start, CommunicationID.MainBoard);
        }
        #endregion
    }
}
