using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using AR;

namespace Project
{
	public partial class FMain
	{
		public Boolean[] DisableMotion;
		private void Mot_PositionChanged(object sender, arDev.MOT.PositionChangeEventArgs e)
		{
			eAxis mot = (eAxis)e.Axis;
			if (mot == eAxis.PX_PICK)
			{

			}

			//모터 위치가 변경되면 로더 컨트롤에 입력한다
			hmi1.arMotorPosition[e.Axis] = e.Actual;
		}

		void mot_StatusChanged(object sender, arDev.MOT.StatusChangeEventArags e)
		{
			if (e.Axis >= SETTING.System.MotaxisCount) return;
			if (e.Status == arDev.MOT.MOTION_STATUS.SERVOALARM) hmi1.arMOT_Alm[e.Axis] = e.Value;
			else if (e.Status == arDev.MOT.MOTION_STATUS.LIMITN) hmi1.arMOT_LimDn[e.Axis] = e.Value;
			else if (e.Status == arDev.MOT.MOTION_STATUS.LIMITP) hmi1.arMOT_LimUp[e.Axis] = e.Value;
			else if (e.Status == arDev.MOT.MOTION_STATUS.ORIGIN) hmi1.arMOT_Origin[e.Axis] = e.Value;
			else if (e.Status == arDev.MOT.MOTION_STATUS.SERVROON) hmi1.arMOT_SVOn[e.Axis] = e.Value;
		}

		private void Mot_EndStatusChanged(object sender, arDev.MOT.EndStatusChangeEventArgs e)
		{
			if (AR.SETTING.Data.Enable_Log_MotStopReason == false) return;  //210112

			var bitstatus = Convert.ToString(e.Value, 2).PadLeft(16, '0');
			List<FS_END_STATUS> lst = new List<FS_END_STATUS>();
			for (byte i = 0; i < 15; i++)
			{
				var offset = (ushort)(Math.Pow(2, i));
				if ((e.Value & offset) > 0) lst.Add((FS_END_STATUS)offset);
			}

			var reason = string.Join(",", lst);
			PUB.log.Add("MOT", $"Motor stop reason ({e.axis}): {reason}: bit={bitstatus}");
		}


		void mot_HomeStatusChanged(object sender, arDev.MOT.HomeStatusChangeEventArgs e)
		{
			if (PUB.sm.Step == eSMStep.HOME_FULL)
			{
				hmi1.arHomeProgress[e.Axis] = e.Progress;
				if (e.NewStatus == arDev.MOT.HOME_RESULT.HOME_ERR_NOT_DETECT)
				{
					//홈 검색시 오류가 발생했다 사용자에게 알림을 해야 함
					PUB.Result.SetResultMessage(eResult.MOTION, eECode.MOT_HSET, eNextStep.ERROR, e.Axis);
				}
				else if (e.NewStatus == arDev.MOT.HOME_RESULT.HOME_SUCCESS)
				{
					PUB.log.AddI(string.Format("Home search completed for axis: {0}", e.Axis));
				}
			}
		}


		void mot_Message(object sender, arDev.MOT.MessageEventArgs e)
		{
			if (e.IsError)
			{
				if (e.Message.IndexOf("same position") != -1 || e.Message.IndexOf("inposition") != -1)
				{  // Pub.log.AddAT("MOT:" + e.Message);
				}
				else PUB.log.AddE("MOT:" + e.Message);
			}

			else PUB.log.Add("MOT:" + e.Message);
		}

	}
}
