package SCHUNK.EndOfArm.impl;


import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import javax.imageio.ImageIO;

import com.ur.urcap.api.contribution.InstallationNodeContribution;
import com.ur.urcap.api.domain.URCapAPI;
import com.ur.urcap.api.domain.data.DataModel;
import com.ur.urcap.api.domain.script.ScriptWriter;
import com.ur.urcap.api.ui.annotation.Img;
import com.ur.urcap.api.ui.annotation.Input;
import com.ur.urcap.api.ui.annotation.Label;
import com.ur.urcap.api.ui.annotation.Select;
import com.ur.urcap.api.ui.component.ImgComponent;
import com.ur.urcap.api.ui.component.InputButton;
import com.ur.urcap.api.ui.component.InputEvent;
import com.ur.urcap.api.ui.component.InputTextField;
import com.ur.urcap.api.ui.component.LabelComponent;
import com.ur.urcap.api.ui.component.SelectDropDownList;
import com.ur.urcap.api.ui.component.SelectEvent;




public class GrpInstallationNodeContribution implements InstallationNodeContribution {
	eoa_Language.TextResource getTextResource() {
		return eoa_Language.LanguagePack.getInstance().getTextResource();
	}

	
// Variables	
	private static final String nfTWait = "sTWait_KEY";
	
	
	private static final String DO_System_KEY = "DO_System_KEY";
	
	private static final String DO_Close_No = "DO_Close_No";
	private static final String DO_Open_No  = "DO_Open_No";
	
	private static final String LogoImg = "LogoImg";
	private static final String GrpImg = "GrpImg";
	
	
	private static final String lbl_Title = "lbl_Title";
	private static final String lbl_TWait = "lbl_TWait_KEY";
	private static final String lbl_DO_Open = "lbl_DO_Open_KEY";
	private static final String lbl_DO_Close = "lbl_DO_Close_KEY";
	
	private String Controller = "Controller";
	private String tool = "Tool";
	
	private DataModel model;
	private URCapAPI api;
	
	
//HMI-Objects
	// Waittime
	@Input (id = nfTWait)
	public InputTextField sTWaitField;
	
	@Label (id = lbl_TWait)
	public LabelComponent lb_TWait;
	@Label (id = lbl_DO_Open)
	public LabelComponent lb_DO_Open;
	@Label (id = lbl_DO_Close)
	public LabelComponent lb_DO_Close;
	@Label (id = lbl_Title)
	public LabelComponent lb_Title;
	
	//DIO Gripper Open/Close
	@Select (id = DO_System_KEY)
	public SelectDropDownList DO_System;
	@Input (id = DO_Close_No)
	public InputTextField DONo_Close;
	@Input (id = DO_Open_No)
	public InputTextField DONo_Open;

	//Images
	@Img(id = LogoImg)
	public ImgComponent ImgLogo;
	@Img(id = GrpImg)
	public ImgComponent ImgGrp;
	
	public GrpInstallationNodeContribution(URCapAPI api, DataModel model) {
		this.model = model;
		this.api = api;
	}

// Events
	// Set TWait
	@Input(id = nfTWait)
	private void on_TWait_Change(InputEvent event){
		if (event.getEventType()==InputEvent.EventType.ON_CHANGE){
			set_fTWait(Float.valueOf(sTWaitField.getText().replace(",", ".")));			
		}
	}
	@Input(id = DO_Open_No)
	private void on_DO_No_Open_Change(InputEvent event){
		if (event.getEventType()==InputEvent.EventType.ON_CHANGE){
			if (Integer.valueOf(DONo_Open.getText())>1 && DO_System.getSelectedItem().equals(tool)){
				DONo_Open.setText("1");
				Create_Popup(getTextResource().get_Error_IO_Config() );
			}
		}
	}
	@Input(id = DO_Close_No)
	private void on_DO_No_Close_Change(InputEvent event){
		if (event.getEventType()==InputEvent.EventType.ON_CHANGE){
			if (Integer.valueOf(DONo_Close.getText())>1 && DO_System.getSelectedItem().equals(tool)){
				DONo_Close.setText("0");
				Create_Popup(getTextResource().get_Error_IO_Config() );
		}
		}
	}
	@Select(id = DO_System_KEY)
	private void onSelect_Close_Change(SelectEvent event){
		if (event.getEvent()==SelectEvent.EventType.ON_SELECT){
			setTool();
				
		}
	}
	private void setTool(){
		if (DO_System.getSelectedItem().equals(tool)){
			DONo_Close.setText("1");
			DONo_Close.setEnabled(false);
			DONo_Open.setText("0");
			DONo_Open.setEnabled(false);
		}else{
			DONo_Close.setEnabled(true);
			DONo_Open.setEnabled(true);
		}
	}
	

	@Override
	public void openView() {
		// Set Language Settings
			lb_TWait.setText(getTextResource().get_TWait());
			lb_DO_Close.setText(getTextResource().get_DO_Close());
			lb_DO_Open.setText(getTextResource().get_DO_Open());
			lb_Title.setText(getTextResource().getTitle());
			sTWaitField.setText(String.valueOf(get_fTWait()));
			
			addItems_DIO(DO_System);
			
			DO_System.selectItem(get_DO_Sys());
			setTool();
			DONo_Close.setText(get_DONo_Close());
			DONo_Open.setText(get_DONo_Open());
		try{
				ImgLogo.setImage(ImageIO.read(getClass().getResource(getTextResource().get_Path_To_Logo_Image())));
				ImgGrp.setImage(ImageIO.read(getClass().getResource(getTextResource().get_Path_To_Gripper_Image())));
			}catch  (java.io.IOException e){
				e.printStackTrace();
			}
	}
	
	@Override
	public void closeView() { 
		if (DONo_Close.getText().equals(DONo_Open.getText())){
			Create_Popup(getTextResource().get_Error_IO_Config() );
		}

			// Set Variables of the IO Config
			set_DONo_Close(DONo_Close.getText());
			set_DONo_Open(DONo_Open.getText());
			
			set_DO_Sys(String.valueOf(DO_System.getSelectedItem()));
	}

	public boolean isDefined() {
		return true;
	}

	@Override
	public void generateScript(ScriptWriter writer) {	
		String set_Open_True   = ln_DO(get_DO_Sys(), get_DONo_Open(),  "True");
		String set_Open_False  = ln_DO(get_DO_Sys(), get_DONo_Open(),  "False");
		String set_Close_True  = ln_DO(get_DO_Sys(),get_DONo_Close(), "True");
		String set_Close_False = ln_DO(get_DO_Sys(),get_DONo_Close(), "False");
			
		// Check IO-Configuration
				if (set_Open_True.equals(set_Close_True)){
			writer.appendLine("popup(\"" + getTextResource().get_Error_IO_Config()+"\")");
			writer.appendLine("halt");
		}
		
		if(get_DO_Sys() == tool ||get_DO_Sys() == tool){
		writer.appendLine("set_tool_voltage(24)");
		}
	// Set new function: Open Gripper
		writer.appendLine("def EoaGrpOpen():");
			writer.appendLine(set_Close_False);
			writer.sleep(0.015);
			writer.appendLine(set_Open_True);
			writer.sleep(get_fTWait());
		writer.appendLine("end");	// end function GrpOpen
		
		
		
	// set new function: Close Gripper
		writer.appendLine("def EoaGrpClose():");
			writer.appendLine(set_Open_False);		
			writer.sleep(0.015);
			writer.appendLine(set_Close_True);
			writer.sleep(get_fTWait());

			writer.appendLine("end");	// end function GrpClose
	}

	
	private void addItems_DIO(SelectDropDownList DIO){
		DIO.removeAllItems();
		DIO.addItem(tool);
		DIO.addItem(Controller);
	
	
	}
	private String ln_DO(String Sys, String No, String value){
		String ln = "";
		
		if (Sys.equals(tool)){
			ln ="set_tool_digital_out(" + No + ", " + value + ")";
		}else{
			ln ="set_digital_out(" + No + ", " + value + ")";	
		}
		return ln;
	}

	//Set Variables in DataModel
	private void set_fTWait(float fValue){
		model.set("fTWait", fValue);
	}
	public void set_DONo_Open(String value){
		model.set("DO_No_Open", value);
	}
	public void set_DONo_Close(String value){
		model.set("DO_No_Close", value);
	}

	public void set_DO_Sys(String value){
		model.set("DO_System", value);
	}
	
	// get Set Variables in DataModel
	private float get_fTWait(){
		return (float) model.get("fTWait", 0.5);
	}
	public String get_DONo_Open(){
		return model.get("DO_No_Open", "0");
	}
	public String get_DONo_Close(){
		return model.get("DO_No_Close","1");
	}	
	public String get_DO_Sys(){
		return model.get("DO_System", tool);
	}

	// For direct Movement: Close Gripper
	// Will be called in ProgNode
	public String get_DO_Close(){
		if (get_DO_Sys().equals(tool)){
			return "tool_out["+ get_DONo_Close()+"]";
		} else{
			return "digital_out[" +get_DONo_Close()+"]";
		}
	}
	
	// For direct Movement: Open Gripper
	// Will be called in ProgNode
	public String get_DO_Open(){
		if (get_DO_Sys().equals(tool)){
			return "tool_out["+ get_DONo_Open()+"]";
		} else{
			return "digital_out[" +get_DONo_Open()+"]";
		}
	}
	private void Create_Popup(String str){
		str = "popup(\""+str+"\")";
		SocketAddress me = new InetSocketAddress("127.0.0.1", 30001);
		Socket socket = new Socket();
		try {
			socket.connect(me,2000);
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
				out.println(str);
			out.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}