// MACRO PRESETTING V 1.3 20-03-2019
// Inizio inizializzare variabile

if (!checkButton)
{
	return;
}

checkButton = false;

InitializeGUI ();
dr = new DialogResult ();

OldTool = Convert.ToDouble (exec.Getcurrenttool ());

X_palp = Convert.ToDouble (AS3.Getfield (3001));			//posizione X del palpatore 
Y_palp = Convert.ToDouble (AS3.Getfield (3002));			//posizione Y del palpatore
X_UT1 = Convert.ToDouble (AS3.Getfield (3003));
Y_UT1 = Convert.ToDouble (AS3.Getfield (3004));
ToolYFuori = Y_UT1-50;   										// Y fuori rastelliera
ToolDown = Convert.ToDouble (AS3.Getfield (3005)); 			// DISTANZA DISCESA SU PORTAUTENSILE
UTpres = Convert.ToDouble (AS3.Getfield (3006));			// posizione maassima presetting
ToolUpUscita = ToolDown + 45; // sale di 45 mm rispetto alla quota di cambio

offsetToolPosition = Convert.ToDouble(exec.Readkey ("GP Proto CNC", "offsetToolPosition", "0"));
maxToolNumber = Convert.ToInt32(exec.Readkey ("GP Proto CNC", "maxToolNumber", "0"));
chuckPort = Convert.ToInt32(exec.Readkey ("GP Proto CNC", "chuckPort", "0"));
chuckPin = Convert.ToInt32(exec.Readkey ("GP Proto CNC", "chuckPin", "0"));

if (UTpres > maxToolNumber)
{
	UTpres = maxToolNumber;
}


// Fine inizializzare variabile

	exec.Callbutton(167);
	AS3.Clearlist (2);
	exec.AddStatusmessage ("-->MACRO PRESETTING V 1.3 .");
	//checkButton = true;
	
if(!exec.GetLED(56)||!exec.GetLED(57)||!exec.GetLED(58)) 		// controllo se la macchina e referenziata.
{
	btnYES.Visible = false;
	btnNO.Visible = false;
	btnOK.Visible = true;
	textBoxStatus.Clear ();
	textBoxStatus.AppendText (" \n");
	textBoxStatus.AppendText ("La macchina deve essere referenziata!");
	System.Media.SystemSounds.Exclamation.Play();
	dr = myForm.ShowDialog ();
				
	if (dr == DialogResult.OK)
	{
		myForm.Close ();
	}
	
	exec.Stop();
	checkButton = true;
	return;
}

if (OldTool< 1)
{
	btnYES.Visible = false;
	btnNO.Visible = false;
	btnOK.Visible = true;
	textBoxStatus.Clear ();
	textBoxStatus.AppendText (" \n");
	textBoxStatus.AppendText ("Nessun utensile in mandrino!");
	System.Media.SystemSounds.Exclamation.Play();
	dr = myForm.ShowDialog ();
				
	if (dr == DialogResult.OK)
	{
		myForm.Close ();
	}

	exec.Stop();
	checkButton = true;
	return;
}


for (NewTool=1; NewTool<= UTpres; NewTool++)
{
	
	exec.Code ("G00 G53 Z" + ToolUp); 				//Z sopra
	while(exec.IsMoving()){}
	AS3.Clearlist (2);
	exec.AddStatusmessage("-->  Utensile in mandrino: " + OldTool);
	exec.AddStatusmessage("-->  Deposita utensile: " + OldTool);

	MovePos(Convert.ToInt32 (OldTool));		// Va alla routine che porta gli assi davanti alla rastrelliera Y fuori										
		exec.AddStatusmessage("-->  Quota di uscita e entra: " + ToolUpUscita);
	exec.Code ("G00 G53 Z" + ToolUpUscita);				//abbassa la Z alla quota di inserimento ************
	while (exec.IsMoving ()) {}
	exec.Code ("G00 G53 Y" + Y_UT1);				//Entra nella rastrelliera
	while (exec.IsMoving ()) {}
	
	exec.Code ("G00 G53 Z" + ToolDown);				//abbassa la Z alla quota di rilascio
	while (exec.IsMoving ()) {}
	exec.Code ("G4 P1");
	
	exec.Setoutpin (chuckPort, chuckPin);				//Apre la pinza ATC
	exec.Code ("G4 P1.0"); 								//Attesa apertura pinza
		exec.AddStatusmessage("-->  Quota di uscita e esce: " + ToolUpUscita);
	exec.Code ("G01 F500 G53 Z" + ToolUpUscita);			//alza la z alla quota di uscita
	while (exec.IsMoving ()) {}
	exec.Code ("G00 G53 Y" + ToolYFuori); 				//Y fuori
	while (exec.IsMoving ()) {}
		exec.Code ("G01 F500 G53 Z" + ToolMove);			//alza la z alla quota di movimento
	while (exec.IsMoving ()) {}
	
	
	
	AS3.Clearlist (2);
	exec.AddStatusmessage ("-->  Nuovo utensile: " + NewTool);
 
	OldTool=NewTool;

	MovePos(NewTool);						//muove verso il nuovo strumento

	exec.Code ("G00 G53 Z" + ToolUpUscita);				//abbassa la Z alla quota di inserimento 
	while (exec.IsMoving ()) {}
	exec.Code ("G00 G53 Y" + Y_UT1);				//Entra nella rastrelliera
	while (exec.IsMoving ()) {}
	
	exec.Code ("G00 G53 Z" + ToolDown);				//abbassa la Z alla quota di rilascio
	while (exec.IsMoving ()) {}
		
	
	exec.Code ("G4 P2");
	if(!exec.Ismacrostopped()) // If tool change was not interrupted with a stop only then validate new tool number
	{
		exec.Clroutpin (chuckPort, chuckPin); 					//Chiude la pinza ATC
	}
	exec.Code ("G4 P2"); 										//prende lo strumento *************************
	
		exec.Code ("G01 F500 G53 Z" + ToolUpUscita);			//alza la z alla quota di uscita
	while (exec.IsMoving ()) {}
	exec.Code ("G00 G53 Y" + ToolYFuori); 				//Y fuori
	while (exec.IsMoving ()) {}	
	
	exec.Code ("G01 F700 G53 Z" + ToolUp);				//alza la Z
	while (exec.IsMoving ()) {}
	
	if(!exec.Ismacrostopped()) 
	{
		exec.Setcurrenttool (NewTool);

	}
	else
	{
		exec.StopWithDeccel();
		
		InitializeGUI ();
		btnYES.Visible = false;
		btnNO.Visible = false;
		btnOK.Visible = true;
		textBoxStatus.Clear ();
		textBoxStatus.AppendText (" \n");
		textBoxStatus.AppendText ("Operazione terminata dall'operatore!");
		System.Media.SystemSounds.Exclamation.Play();
		dr = myForm.ShowDialog ();
				
		if (dr == DialogResult.OK)
		{
			myForm.Close ();
		}
		checkButton = true;
		return;
	}
	
//+++++++++++++++++++++++ROUTINE DI MISURA ++++++++++++++++++


	exec.Code ("G0 G53 Y" + ToolYFuori); 				//Y fuori
	while (exec.IsMoving ()) {}

	//mi allineo sul palpatore

	exec.Code ("G1 G53 X" + X_palp + "F" + fmax); 
	while (exec.IsMoving ()) {}
	exec.Code ("G1 G53 Y" + Y_palp + "F" + fmax); 
	while (exec.IsMoving ()) {}
	AS3.Clearlist (2);
	exec.AddStatusmessage ("-->  Tool No." + NewTool + " misura.");

	//scendo sul palpatore per vedere la misura della punta attuale
	exec.Code ("F" + fminZ);
	exec.Code ("G31 Z" + zmin);
	while (exec.IsMoving ()) {}

	Zuno = exec.Getvar (5063);					//memorizzo il valore di Z della punta attuale

	if (NewTool == 1)
	{
		if(!exec.Ismacrostopped()) 
		{
			Zzero = Zuno;
			counter = (196 + NewTool) - 1;
			AS3.Setfield (0.0000, counter);
			AS3.Validatefield (counter);
		}
		else
		{
			exec.StopWithDeccel();
		  
		  	InitializeGUI ();
			btnYES.Visible = false;
			btnNO.Visible = false;
			btnOK.Visible = true;
			textBoxStatus.Clear ();
			textBoxStatus.AppendText (" \n");
			textBoxStatus.AppendText ("Operazione terminata dall'operatore!");
			System.Media.SystemSounds.Exclamation.Play();
			dr = myForm.ShowDialog ();
				
			if (dr == DialogResult.OK)
			{
				myForm.Close ();
			}
			checkButton = true;
			return;
		}
	}
	else
	{
		if(!exec.Ismacrostopped()) 
		{
			Zdelta = Zuno - Zzero;
			counter = (196 + NewTool) - 1;
			AS3.Setfield (Zdelta, counter);
			AS3.Validatefield (counter);
		}
		else
		{
			exec.StopWithDeccel();
		  
		  	InitializeGUI ();
			btnYES.Visible = false;
			btnNO.Visible = false;
			btnOK.Visible = true;
			textBoxStatus.Clear ();
			textBoxStatus.AppendText (" \n");
			textBoxStatus.AppendText ("Operazione terminata dall'operatore!");
			System.Media.SystemSounds.Exclamation.Play();
			dr = myForm.ShowDialog ();
				
			if (dr == DialogResult.OK)
			{
				myForm.Close ();
			}
			checkButton = true;
			return;
		}
	}

	exec.Code ("G01 F700 G53 Z" + ToolUp);					//alza la z
	while (exec.IsMoving ()) {}
	exec.Code ("G00 G53 Y" + ToolYFuori); 					//Y fuori
	while (exec.IsMoving ()) {}
	Zuno = exec.GetZpos ();							//memorizzo il valore di Z della punta attuale

}

	//Muovo verso origine pezzo e salvo i valori
	exec.Code ("G00 G53 Z" + ToolUp);				//Z sopra
	while (exec.IsMoving ()) {}
	exec.Callbutton(167);
	AS3.Clearlist (2);
	exec.AddStatusmessage ("-->  Procedura di presetting completata.");
	checkButton = true;


	
#Events

// Start global variables 

int NewTool = 0;
int ToolUp = -5; 		// Z Hieght to Rapid from tool to tool
int ToolMove= -45; 		// movimento mentre cambia
int fminZ = 200;
int fmin = 1000;
int fmax = 5000;
int zmin = -200;
int counter = 0;

double OldTool;			//Utensile in mandrino
double X_palp;			//posizione X del palpatore (Settings -> Tool Change Location)
double Y_palp;			//posizione Y del palpatore
double X_UT1;
double Y_UT1;
double ToolYFuori;   		// Y fuori rastelliera
double ToolDown; 		// DISTANZA DISCESA SU PORTAUTENSILE
double UTpres;			// posizione maassima presetting
double ToolUpUscita; 			// Quota di movimento su cambio utensile per uscire dalla rastrelliera
double XPos, YPos;

double SafeZ = -10;
double SafeZup = 0;




double offsetToolPosition;
int maxToolNumber;
int chuckPort;
int chuckPin;

double Zzero = 0;
double Zuno = 0;
double Zdelta = 0;

static bool checkButton = true;

Form myForm;
Button btnYES;
Button btnNO;
Button btnOK;
TextBox textBoxStatus;
PictureBox pictureBoxUI;
DialogResult dr;

public Point mouseLocation;

// End global variables



void MovePos(int NumeroUtensile) // Muove verso la posizione utennsile e rimane fuori dalla rastrelliera
{
	if (NumeroUtensile==1)
	{
		XPos = X_UT1;
		YPos = ToolYFuori;
	}
	else
	{
		XPos = X_UT1+(offsetToolPosition*(NumeroUtensile-1));
		YPos = ToolYFuori;
	}
	
exec.Code ("G01 F2000 G53 X" + XPos);
while(exec.IsMoving()){}
exec.Code ("G01 F2000 G53 Y" + YPos);
while(exec.IsMoving()){}
AS3.Clearlist (2);
exec.AddStatusmessage ("-->  X = " + XPos + " Y = " + YPos);
exec.AddStatusmessage ("-->  Position of tool No." + NumeroUtensile);
}

private void pictureBoxUI_MouseDown(object sender, MouseEventArgs e)
{
	mouseLocation = new Point(-e.X, -e.Y);
}

private void pictureBoxUI_MouseMove(object sender, MouseEventArgs e)
{
	if (e.Button == MouseButtons.Left)
	{
		Point mousePos = Control.MousePosition;
		mousePos.Offset(mouseLocation.X, mouseLocation.Y);
		myForm.Location = mousePos;
	}
}

private void InitializeGUI ()
{
btnYES = new Button ();
btnYES.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(164)))), ((int)(((byte)(211)))), ((int)(((byte)(118)))));
btnYES.DialogResult = System.Windows.Forms.DialogResult.Yes;
btnYES.FlatAppearance.BorderSize = 0;
btnYES.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
btnYES.Font = new System.Drawing.Font("Aero Matics", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
btnYES.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(52)))), ((int)(((byte)(63)))));
btnYES.Location = new System.Drawing.Point(236, 112);
btnYES.Size = new System.Drawing.Size(70, 22);
btnYES.TabIndex = 1;
btnYES.Text = "YES";
btnYES.UseVisualStyleBackColor = false;

btnNO = new Button ();
btnNO.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(164)))), ((int)(((byte)(211)))), ((int)(((byte)(118)))));
btnNO.DialogResult = System.Windows.Forms.DialogResult.No;
btnNO.FlatAppearance.BorderSize = 0;
btnNO.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
btnNO.Font = new System.Drawing.Font("Aero Matics", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
btnNO.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(52)))), ((int)(((byte)(63)))));
btnNO.Location = new System.Drawing.Point(315, 112);
btnNO.Size = new System.Drawing.Size(70, 22);
btnNO.TabIndex = 2;
btnNO.Text = "NO";
btnNO.UseVisualStyleBackColor = false;

btnOK = new Button ();
btnOK.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(164)))), ((int)(((byte)(211)))), ((int)(((byte)(118)))));
btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
btnOK.FlatAppearance.BorderSize = 0;
btnOK.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
btnOK.Font = new System.Drawing.Font("Aero Matics", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
btnOK.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(52)))), ((int)(((byte)(63)))));
btnOK.Location = new System.Drawing.Point(315, 112);
btnOK.Size = new System.Drawing.Size(70, 22);
btnOK.TabIndex = 3;
btnOK.Text = "OK";
btnOK.UseVisualStyleBackColor = false;

textBoxStatus = new TextBox (); 
textBoxStatus.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(40)))), ((int)(((byte)(52)))), ((int)(((byte)(63)))));
textBoxStatus.BorderStyle = System.Windows.Forms.BorderStyle.None;
textBoxStatus.Font = new System.Drawing.Font("Aero Matics", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
textBoxStatus.ForeColor = System.Drawing.Color.LightGray;
textBoxStatus.Location = new System.Drawing.Point(83, 39);
textBoxStatus.Multiline = true;
textBoxStatus.ReadOnly = true;
textBoxStatus.Size = new System.Drawing.Size(302, 54);
textBoxStatus.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
textBoxStatus.TabIndex = 4;
textBoxStatus.TabStop = false;

pictureBoxUI = new PictureBox ();
pictureBoxUI.BackColor = System.Drawing.Color.Transparent;
pictureBoxUI.BackgroundImage = System.Drawing.Image.FromFile (Application.StartupPath + @"\Flashscreen\BMP\Bluescreenset\MessageBox.png");
pictureBoxUI.Location = new System.Drawing.Point(0, 0);
pictureBoxUI.Size = new System.Drawing.Size(400, 150);
pictureBoxUI.Controls.Add(btnYES);
pictureBoxUI.Controls.Add(btnNO);
pictureBoxUI.Controls.Add(btnOK);
pictureBoxUI.Controls.Add(textBoxStatus);
pictureBoxUI.TabIndex = 0;
pictureBoxUI.MouseDown += new System.Windows.Forms.MouseEventHandler(pictureBoxUI_MouseDown);
pictureBoxUI.MouseMove += new System.Windows.Forms.MouseEventHandler(pictureBoxUI_MouseMove);

myForm = new Form ();
myForm.BackColor = System.Drawing.Color.DarkRed;
myForm.ClientSize = new System.Drawing.Size(400, 150);
myForm.Controls.Add(pictureBoxUI);
myForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
myForm.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
myForm.TransparencyKey = System.Drawing.Color.DarkRed;
myForm.TopMost = true;
}
              
